diff --git a/App.tsx b/App.tsx index 4a263a03c..2948dda69 100755 --- a/App.tsx +++ b/App.tsx @@ -55,7 +55,7 @@ import { PassphraseModal, PassphraseRequest } from './components/PassphraseModal import { cn } from './lib/utils'; import { classifyLocalShellType } from './lib/localShell'; import { useDiscoveredShells, resolveShellSetting } from './lib/useDiscoveredShells'; -import { ConnectionLog, Host, HostProtocol, SerialConfig, TerminalSession, TerminalTheme } from './types'; +import { ConnectionLog, Host, HostProtocol, SerialConfig, SSHKey, TerminalSession, TerminalTheme } from './types'; import { LogView as LogViewType } from './application/state/useSessionState'; import type { SftpView as SftpViewComponent } from './components/SftpView'; import type { TerminalLayer as TerminalLayerComponent } from './components/TerminalLayer'; @@ -196,6 +196,21 @@ async function loadDefaultKeyPassphrase(keyPath: string): Promise return (await decryptField(enc)) ?? null; } +function removeDefaultKeyPassphrases(keyPaths: string[]): void { + const store = localStorageAdapter.read>(STORAGE_KEY_DEFAULT_KEY_PASSPHRASES); + if (!store) return; + let changed = false; + for (const keyPath of keyPaths) { + if (keyPath in store) { + delete store[keyPath]; + changed = true; + } + } + if (changed) { + localStorageAdapter.write(STORAGE_KEY_DEFAULT_KEY_PASSPHRASES, store); + } +} + function App({ settings }: { settings: SettingsState }) { const { t } = useI18n(); @@ -280,6 +295,7 @@ function App({ settings }: { settings: SettingsState }) { managedSources, updateHosts, updateKeys, + importOrReuseKey, updateIdentities, updateProxyProfiles, updateSnippets, @@ -301,6 +317,9 @@ function App({ settings }: { settings: SettingsState }) { updateGroupConfigs, } = useVaultState(); + const keysRef = useRef(keys); + keysRef.current = keys; + const { sessions, workspaces, @@ -1002,11 +1021,25 @@ function App({ settings }: { settings: SettingsState }) { const unsubscribe = bridge.onPassphraseRequest(async (request) => { console.log('[App] Passphrase request received:', request); - // Try to load saved passphrase and auto-respond + // Check if a reference key exists for this path — use its passphrase + const currentKeys = keysRef.current; + const refKey = currentKeys.find((k: SSHKey) => k.source === 'reference' && k.filePath === request.keyPath); + if (refKey?.passphrase && refKey.savePassphrase !== false) { + console.log('[App] Auto-responding with reference key passphrase for:', request.keyPath); + void bridge.respondPassphrase?.(request.requestId, refKey.passphrase, false); + return; + } + + // Fallback: try old storage for passphrase const saved = await loadDefaultKeyPassphrase(request.keyPath); if (saved) { console.log('[App] Auto-responding with saved passphrase for:', request.keyPath); void bridge.respondPassphrase?.(request.requestId, saved, false); + // Migrate to reference key if one exists + if (refKey && !refKey.passphrase) { + const updated = currentKeys.map((k: SSHKey) => k.id === refKey.id ? { ...k, passphrase: saved, savePassphrase: true } : k); + void updateKeys(updated); + } return; } @@ -1037,10 +1070,17 @@ function App({ settings }: { settings: SettingsState }) { if (remember && request?.keyPath) { console.log('[App] Saving passphrase for:', request.keyPath); void saveDefaultKeyPassphrase(request.keyPath, passphrase); + // Also save to matching reference key + const currentKeys = keysRef.current; + const refKey = currentKeys.find((k: SSHKey) => k.source === 'reference' && k.filePath === request.keyPath); + if (refKey) { + const updated = currentKeys.map((k: SSHKey) => k.id === refKey.id ? { ...k, passphrase, savePassphrase: true } : k); + void updateKeys(updated); + } } setPassphraseQueue(prev => prev.filter(r => r.requestId !== requestId)); - }, [passphraseQueue]); + }, [passphraseQueue, updateKeys]); // Handle passphrase cancel const handlePassphraseCancel = useCallback((requestId: string) => { @@ -1083,6 +1123,21 @@ function App({ settings }: { settings: SettingsState }) { }; }, []); + // Handle passphrase auth failure (saved passphrase was wrong, clear it) + useEffect(() => { + const bridge = netcattyBridge.get(); + if (!bridge?.onPassphraseAuthFailed) return; + + const unsubscribe = bridge.onPassphraseAuthFailed((event) => { + console.log('[App] Passphrase auth failed for keys:', event.keyPaths); + removeDefaultKeyPassphrases(event.keyPaths); + }); + + return () => { + unsubscribe?.(); + }; + }, []); + // Debounce ref for moveFocus to prevent double-triggering when focus switches const lastMoveFocusTimeRef = useRef(0); const MOVE_FOCUS_DEBOUNCE_MS = 200; @@ -1923,6 +1978,7 @@ function App({ settings }: { settings: SettingsState }) { onUpdateGroupConfigs={updateGroupConfigs} onUpdateHosts={updateHosts} onUpdateKeys={updateKeys} + onImportOrReuseKey={importOrReuseKey} onUpdateIdentities={updateIdentities} onUpdateProxyProfiles={updateProxyProfiles} onUpdateSnippets={updateSnippets} diff --git a/application/i18n/locales/en.ts b/application/i18n/locales/en.ts index c46a6c08e..b8b4611fd 100644 --- a/application/i18n/locales/en.ts +++ b/application/i18n/locales/en.ts @@ -1687,6 +1687,7 @@ const en: Messages = { 'keychain.edit.publicKey': 'Public key', 'keychain.edit.certificate': 'Certificate', 'keychain.edit.certificatePlaceholder': 'Certificate content (optional)', + 'keychain.edit.filePath': 'File path', 'keychain.edit.keyExport': 'Key export', 'keychain.edit.exportToHost': 'Export to host', diff --git a/application/i18n/locales/zh-CN.ts b/application/i18n/locales/zh-CN.ts index 589ac61b5..8a7919ac3 100644 --- a/application/i18n/locales/zh-CN.ts +++ b/application/i18n/locales/zh-CN.ts @@ -1696,6 +1696,7 @@ const zhCN: Messages = { 'keychain.edit.publicKey': '公钥', 'keychain.edit.certificate': '证书', 'keychain.edit.certificatePlaceholder': '证书内容(可选)', + 'keychain.edit.filePath': '文件路径', 'keychain.edit.keyExport': '密钥导出', 'keychain.edit.exportToHost': '导出到主机', diff --git a/application/state/useVaultState.ts b/application/state/useVaultState.ts index bc630c86b..affad63a2 100644 --- a/application/state/useVaultState.ts +++ b/application/state/useVaultState.ts @@ -159,6 +159,42 @@ export const useVaultState = () => { }); }, []); + const importOrReuseKey = useCallback((draft: Partial): SSHKey => { + const existing = keys.find((k) => { + if (draft.source === 'reference' && draft.filePath) { + return k.source === 'reference' && k.filePath === draft.filePath; + } + if (draft.privateKey) { + return k.privateKey === draft.privateKey; + } + return false; + }); + if (existing) return existing; + + const newKey: SSHKey = { + id: crypto.randomUUID(), + label: draft.label || 'Imported Key', + type: draft.type || 'ED25519', + privateKey: draft.privateKey || '', + publicKey: draft.publicKey, + certificate: draft.certificate, + passphrase: draft.passphrase, + savePassphrase: draft.savePassphrase, + source: draft.source || 'imported', + category: (draft.category || 'key') as KeyCategory, + created: Date.now(), + filePath: draft.filePath, + }; + const updated = [...keys, newKey]; + setKeys(updated); + const ver = ++keysWriteVersion.current; + void encryptKeys(updated).then((enc) => { + if (ver === keysWriteVersion.current) + localStorageAdapter.write(STORAGE_KEY_KEYS, enc); + }); + return newKey; + }, [keys]); + const updateIdentities = useCallback((data: Identity[]) => { setIdentities(data); const ver = ++identitiesWriteVersion.current; @@ -727,6 +763,7 @@ export const useVaultState = () => { groupConfigs, updateHosts, updateKeys, + importOrReuseKey, updateIdentities, updateProxyProfiles, updateSnippets, diff --git a/components/HostDetailsPanel.tsx b/components/HostDetailsPanel.tsx index 510cb8d16..94be72c45 100644 --- a/components/HostDetailsPanel.tsx +++ b/components/HostDetailsPanel.tsx @@ -153,6 +153,7 @@ interface HostDetailsPanelProps { groupDefaults?: Partial; groupConfigs?: GroupConfig[]; layout?: AsidePanelLayout; + onImportKey?: (draft: Partial) => SSHKey; } const HostDetailsPanel: React.FC = ({ @@ -174,6 +175,7 @@ const HostDetailsPanel: React.FC = ({ groupDefaults, groupConfigs = [], layout = "overlay", + onImportKey, }) => { const { t } = useI18n(); const { checkSshAgent } = useApplicationBackend(); @@ -1316,11 +1318,27 @@ const HostDetailsPanel: React.FC = ({ onKeyDown={(e) => { if (e.key === "Enter" && newKeyFilePath.trim()) { e.preventDefault(); - const paths = [...(form.identityFilePaths || []), newKeyFilePath.trim()]; - update("identityFilePaths", paths); - update("identityFileId", undefined); - update("authMethod", "key"); + const path = newKeyFilePath.trim(); + if (onImportKey) { + const fileName = path.split('/').pop() || path; + const key = onImportKey({ + source: 'reference', + filePath: path, + label: fileName, + privateKey: '', + category: 'key', + }); + update("identityFileId", key.id); + update("identityFilePaths", undefined); + update("authMethod", "key"); + } else { + const paths = [...(form.identityFilePaths || []), path]; + update("identityFilePaths", paths); + update("identityFileId", undefined); + update("authMethod", "key"); + } setNewKeyFilePath(""); + setSelectedCredentialType(null); } }} /> @@ -1338,10 +1356,25 @@ const HostDetailsPanel: React.FC = ({ [{ name: "All Files", extensions: ["*"] }] ); if (filePath) { - const paths = [...(form.identityFilePaths || []), filePath]; - update("identityFilePaths", paths); - update("identityFileId", undefined); - update("authMethod", "key"); + if (onImportKey) { + const fileName = filePath.split('/').pop() || filePath; + const key = onImportKey({ + source: 'reference', + filePath, + label: fileName, + privateKey: '', + category: 'key', + }); + update("identityFileId", key.id); + update("identityFilePaths", undefined); + update("authMethod", "key"); + } else { + const paths = [...(form.identityFilePaths || []), filePath]; + update("identityFilePaths", paths); + update("identityFileId", undefined); + update("authMethod", "key"); + } + setSelectedCredentialType(null); } }} > diff --git a/components/KeychainManager.tsx b/components/KeychainManager.tsx index 8653426a5..bbb3e71ce 100644 --- a/components/KeychainManager.tsx +++ b/components/KeychainManager.tsx @@ -3,6 +3,9 @@ import { ChevronDown, ChevronRight, Edit2, + Eye, + EyeOff, + FileKey, Info, Key, LayoutGrid, @@ -175,7 +178,7 @@ echo $3 >> "$FILE"`); switch (activeFilter) { case "key": result = result.filter( - (k) => k.source === "generated" || k.source === "imported", + (k) => k.source === "generated" || k.source === "imported" || k.source === "reference", ); break; case "certificate": @@ -1140,71 +1143,134 @@ echo $3 >> "$FILE"`); /> -
- -