Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(ssh): clarify host key failures and add safe recovery (#5691)
Chris Zhangee9ca7660ae1
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/connectFailure.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/connectFailure.test.tsindex f9a4ff3c7b..2b81604650 100644--- a/apps/desktop/src/main/remote-ssh/__tests__/connectFailure.test.ts+++ b/apps/desktop/src/main/remote-ssh/__tests__/connectFailure.test.ts@@ -16,6 +16,11 @@ import {import { classifyConnectFailure } from '../connect-failure.js';describe('classifyConnectFailure', () => {+ it('keeps host verification separate from login and ignores forged server text', () => {+ const error = Object.assign(new Error('SSH host key changed'), { code: 'SSH_HOST_KEY_MISMATCH' });+ expect(classifyConnectFailure(error).code).toBe('SSH_HOST_KEY_MISMATCH');+ expect(classifyConnectFailure(new Error('SSH_HOST_KEY_MISMATCH')).code).toBe('SSH_CONNECT_FAILED');+ });it('classifies the resolveAuth ENOENT error as SSH_KEY_FILE_NOT_FOUND via its stable local code', () => {const err = new Error(`identity file not found: C:\\Users\\someone\\.ssh\\id_ed25519`);(err as { code?: string }).code = KEY_FILE_NOT_FOUND_CODE;diff --git a/apps/desktop/src/main/remote-ssh/__tests__/hostKeyRecovery.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/hostKeyRecovery.test.tsnew file mode 100644index 0000000000..0ebed92b76--- /dev/null+++ b/apps/desktop/src/main/remote-ssh/__tests__/hostKeyRecovery.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it, vi } from 'vitest';+import type { HostSnapshot } from '@cindy/maker-remote-ssh';+import { confirmHostKeyChange } from '../host-key-recovery.js';++function fixture() {+ let snapshot: Pick<HostSnapshot, 'status' | 'hostKeyMismatch'> = {+ status: 'failed',+ hostKeyMismatch: { host: 'server:22', trusted: 'SHA256:old', presented: 'SHA256:new' },+ };+ const host = { snapshot: () => snapshot };+ const options = {+ getHost: vi.fn(() => host),+ store: { replace: vi.fn(async (_key: string, _old: string, _new: string, current: () => boolean) => {+ if (!current()) throw new Error('stale');+ }) },+ confirm: vi.fn(async () => true),+ isWindowAlive: vi.fn(() => true),+ };+ return { options, setSnapshot: (value: typeof snapshot) => { snapshot = value; } };+}++describe('host key recovery confirmation', () => {+ it('replaces exactly the pair displayed in the confirmation', async () => {+ const { options } = fixture();+ await expect(confirmHostKeyChange(options)).resolves.toBe(true);+ expect(options.confirm).toHaveBeenCalledWith({ host: 'server:22', trusted: 'SHA256:old', presented: 'SHA256:new' });+ expect(options.store.replace).toHaveBeenCalledWith('server:22', 'SHA256:old', 'SHA256:new', expect.any(Function));+ });++ it('does not modify trust when the user cancels', async () => {+ const { options } = fixture();+ options.confirm.mockResolvedValue(false);+ await expect(confirmHostKeyChange(options)).resolves.toBe(false);+ expect(options.store.replace).not.toHaveBeenCalled();+ });++ it('does not offer trust changes for a generic connection failure', async () => {+ const { options, setSnapshot } = fixture();+ setSnapshot({ status: 'failed' });+ await expect(confirmHostKeyChange(options)).rejects.toThrow();+ expect(options.confirm).not.toHaveBeenCalled();+ expect(options.store.replace).not.toHaveBeenCalled();+ });++ it.each(['connecting', 'changed-key', 'changed-endpoint', 'removed-host', 'closed-window'])('rejects %s while the confirmation is open', async (change) => {+ const { options, setSnapshot } = fixture();+ options.confirm.mockImplementation(async () => {+ if (change === 'closed-window') options.isWindowAlive.mockReturnValue(false);+ else if (change === 'removed-host') options.getHost.mockReturnValue({ snapshot: () => ({ status: 'failed' }) });+ else if (change === 'connecting') setSnapshot({ status: 'connecting' });+ else setSnapshot({ status: 'failed', hostKeyMismatch: {+ host: change === 'changed-endpoint' ? 'other:22' : 'server:22',+ trusted: 'SHA256:old', presented: change === 'changed-key' ? 'SHA256:third' : 'SHA256:new',+ } });+ return true;+ });+ await expect(confirmHostKeyChange(options)).rejects.toThrow('stale');+ });+});diff --git a/apps/desktop/src/main/remote-ssh/connect-failure.ts b/apps/desktop/src/main/remote-ssh/connect-failure.tsindex 1fd441d540..23a49f4592 100644--- a/apps/desktop/src/main/remote-ssh/connect-failure.ts+++ b/apps/desktop/src/main/remote-ssh/connect-failure.ts@@ -13,6 +13,7 @@ import {} from '@cindy/maker-remote-ssh';export type ConnectFailureClass =+ | 'SSH_HOST_KEY_MISMATCH'| 'SSH_AUTH_FAILED'| 'SSH_KEY_FILE_NOT_FOUND'| 'SSH_AGENT_UNAVAILABLE'@@ -40,6 +41,7 @@ export function classifyConnectFailure(err: unknown): { code: ConnectFailureClas// 失败)统一归 SSH_KEY_FILE_NOT_FOUND(非重试、引导修本地配置)——// 不得落进 SSH_AUTH_FAILED(远端认证语义)或 SSH_CONNECT_FAILED(可重试语义)。const code = (err as { code?: unknown } | null)?.code;+ if (code === 'SSH_HOST_KEY_MISMATCH') return { code, msg };if (code === SSH_CONFIG_AUTH_UNSUPPORTED_CODE) {return { code: 'SSH_CONFIG_AUTH_UNSUPPORTED', msg };}diff --git a/apps/desktop/src/main/remote-ssh/host-key-recovery.ts b/apps/desktop/src/main/remote-ssh/host-key-recovery.tsnew file mode 100644index 0000000000..911e92ff0c--- /dev/null+++ b/apps/desktop/src/main/remote-ssh/host-key-recovery.ts@@ -0,0 +1,30 @@+import type { FileHostKeyStore, HostSnapshot } from '@cindy/maker-remote-ssh';++type Mismatch = NonNullable<HostSnapshot['hostKeyMismatch']>;+interface RecoveryHost {+ snapshot(): Pick<HostSnapshot, 'status' | 'hostKeyMismatch'>;+}++/** Keep confirmation tied to the locally observed endpoint and both fingerprints. */+export async function confirmHostKeyChange(options: {+ getHost: () => RecoveryHost | undefined;+ store: Pick<FileHostKeyStore, 'replace'>;+ confirm: (mismatch: Mismatch) => Promise<boolean>;+ isWindowAlive: () => boolean;+}): Promise<boolean> {+ const host = options.getHost();+ const snapshot = host?.snapshot();+ const mismatch = snapshot?.hostKeyMismatch;+ if (!host || snapshot?.status !== 'failed' || !mismatch) {+ throw new Error('Reconnect to obtain the current host key.');+ }+ if (!await options.confirm(mismatch)) return false;+ await options.store.replace(mismatch.host, mismatch.trusted, mismatch.presented, () => {+ const current = host.snapshot();+ return options.isWindowAlive() && options.getHost() === host && current.status === 'failed'+ && current.hostKeyMismatch?.host === mismatch.host+ && current.hostKeyMismatch.trusted === mismatch.trusted+ && current.hostKeyMismatch.presented === mismatch.presented;+ });+ return true;+}diff --git a/apps/desktop/src/main/remote-ssh/index.ts b/apps/desktop/src/main/remote-ssh/index.tsindex aa493bb0a6..9f22d96b62 100644--- a/apps/desktop/src/main/remote-ssh/index.ts+++ b/apps/desktop/src/main/remote-ssh/index.ts@@ -17,7 +17,8 @@* The pool itself is in-memory; on app restart, hydrate() rebuilds it from disk.*/-import { app, ipcMain, BrowserWindow } from 'electron';+import { app, ipcMain, BrowserWindow, dialog } from 'electron';+import { t } from '../i18n.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import fs from 'node:fs/promises';import path from 'node:path';@@ -75,6 +76,7 @@ import { ensurePiManagerDaemon } from '@cindy/maker-remote-ssh';import { PROTOCOL_VERSION as PI_MANAGER_PROTOCOL_VERSION } from '@cindy/maker-pi-manager';import { invalidateRemotePiPathCaches, redactCredentialText } from '../maker-host/pi-remote-transport.js';import { serializeEnvBlock } from './env-block.js';+import { confirmHostKeyChange } from './host-key-recovery.js';import { classifyConnectFailure } from './connect-failure.js';import {addKeyToAgent,@@ -1414,6 +1416,43 @@ export function registerRemoteSshIpc(): void {});});+ // Local UI only: trust changes require a native confirmation with main-owned details.+ ipcMain.handle('maker:remote-ssh:review-host-key', async (event, args: unknown) => {+ assertTrustedAppRendererEvent(event);+ const id = requireString(requireObject(args).id, 'id');+ const host = getPool().get(id);+ if (!host) throwIpcError('SSH_HOST_NOT_FOUND', `unknown host: ${id}`);+ const store = getSharedHostKeyStore();+ const parent = BrowserWindow.fromWebContents(event.sender);+ if (!parent) throwIpcError('SSH_CONNECT_FAILED', 'The requesting window is no longer available.');+ try {+ const updated = await confirmHostKeyChange({+ getHost: () => getPool().get(id),+ store,+ isWindowAlive: () => !parent.isDestroyed(),+ confirm: async (mismatch) => {+ const result = await dialog.showMessageBox(parent, {+ type: 'warning',+ title: t('settings.remote.hostKey.title'),+ message: t('settings.remote.hostKey.explanation').replace('{{host}}', () => mismatch.host),+ detail: t('settings.remote.hostKey.details')+ .replace('{{trusted}}', () => mismatch.trusted)+ .replace('{{presented}}', () => mismatch.presented)+ .replace('{{file}}', () => store.filePath),+ buttons: [t('settings.remote.hostKey.cancel'), t('settings.remote.hostKey.trust')],+ defaultId: 0,+ cancelId: 0,+ noLink: true,+ });+ return result.response === 1;+ },+ });+ return { updated };+ } catch {+ throwIpcError('SSH_CONNECT_FAILED', t('settings.remote.hostKey.updateFailed'));+ }+ });+ipcMain.handle(REMOTE_SSH_INVOKE.CONNECT, async (_event, args: unknown) => {const obj = requireObject(args);const id = requireString(obj.id, 'id');diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex e9b07f71da..8e3e417395 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4780,6 +4780,8 @@ contextBridge.exposeInMainWorld('electronAPI', {}): Promise<{ host: unknown }> => ipcRenderer.invoke('maker:remote-ssh:update', host),remove: (id: string): Promise<{ ok: true }> =>ipcRenderer.invoke('maker:remote-ssh:remove', { id }),+ reviewHostKey: (id: string): Promise<{ updated: boolean }> =>+ ipcRenderer.invoke('maker:remote-ssh:review-host-key', { id }),connect: (id: string): Promise<{ host: unknown }> =>ipcRenderer.invoke('maker:remote-ssh:connect', { id }),disconnect: (id: string): Promise<{ host: unknown }> =>diff --git a/apps/desktop/src/renderer/components/settings/RemoteSection.tsx b/apps/desktop/src/renderer/components/settings/RemoteSection.tsxindex 2110486ab9..e9f4c9e614 100644--- a/apps/desktop/src/renderer/components/settings/RemoteSection.tsx+++ b/apps/desktop/src/renderer/components/settings/RemoteSection.tsx@@ -50,6 +50,7 @@ interface RowProps {onDisconnect: () => void;onRemove: () => void;onSetupKey: () => void;+ onReviewHostKey: () => void;onEdit: () => void;onToggleAutoConnect: (next: boolean) => void;}@@ -81,6 +82,7 @@ function HostRow({onDisconnect,onRemove,onSetupKey,+ onReviewHostKey,onEdit,onToggleAutoConnect,}: RowProps) {@@ -99,7 +101,10 @@ function HostRow({const via = snap.lastAuthLabel? ` · ${t('settings.remote.viaAuth', { label: snap.lastAuthLabel })}`: '';- const subtitle = snap.lastError && snap.status === 'failed'+ const keyMismatch = snap.status === 'failed' ? snap.hostKeyMismatch : undefined;+ const subtitle = keyMismatch+ ? t('settings.remote.hostKey.explanation', { host: keyMismatch.host })+ : snap.lastError && snap.status === 'failed'? snap.lastError: `${snap.config.user}@${snap.config.hostname}:${snap.config.port}${via}`;@@ -199,7 +204,12 @@ function HostRow({/><span className="text-12">{t('settings.remote.button.autoConnect')}</span></label>- {snap.status === 'failed' && (+ {keyMismatch && (+ <Button variant="secondary" size="md" compact type="button" onClick={onReviewHostKey} disabled={busy}>+ {t('settings.remote.hostKey.review')}+ </Button>+ )}+ {snap.status === 'failed' && !keyMismatch && (<Buttonvariant="secondary"size="md"@@ -1077,7 +1087,9 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}// instead of the generic i18n key, so the user sees the exact// command they need to run.const ipc = extractIpcError(err);- if (ipc?.code === 'SSH_AUTH_FAILED') {+ if (ipc?.code === 'SSH_HOST_KEY_MISMATCH') {+ toast.error(t('settings.remote.hostKey.title'));+ } else if (ipc?.code === 'SSH_AUTH_FAILED') {toast.error(ipc.message);} else if (ipc?.code === 'SSH_KEY_FILE_NOT_FOUND') {// Local key-path problem (fs ENOENT on the configured identityFile),@@ -1095,6 +1107,18 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}}}, [setBusy, t]);+ const handleReviewHostKey = useCallback(async (id: string) => {+ setBusy(id, true);+ try {+ const result = await window.electronAPI.remoteSsh.reviewHostKey(id);+ if (result.updated) await handleConnect(id);+ } catch {+ toast.error(t('settings.remote.hostKey.updateFailed'));+ } finally {+ setBusy(id, false);+ }+ }, [handleConnect, setBusy, t]);+const handleDisconnect = useCallback(async (id: string) => {setBusy(id, true);try {@@ -1356,6 +1380,7 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}onDisconnect={() => handleDisconnect(snap.config.id)}onRemove={() => handleRemove(snap.config.id)}onSetupKey={() => setKeySetupHostId(snap.config.id)}+ onReviewHostKey={() => void handleReviewHostKey(snap.config.id)}onEdit={() => setEditingId(snap.config.id)}onToggleAutoConnect={(next) => void handleSetAutoConnect(snap.config.id, next)}/>diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 0f7a365360..5e12f37ed9 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -740,7 +740,8 @@"PROVIDER_SHARE_CROSS_REGION_DISABLED": "Cross-region sharing isn’t available yet. This link comes from Cindy’s service in another region.","REMOTE_AGENT_SHARE_PAUSED": "Model not changed: the owner has paused this share for you. Pick another model.","REMOTE_AGENT_SHARE_REMOVED": "Model not changed: this share is no longer available (the owner removed it or you left). Pick another model.",- "REMOTE_AGENT_SHARE_UNAVAILABLE": "Model not changed: the shared provider is temporarily unavailable (the owner's computer is offline or sharing is turned off for now). Try again later or pick another model."+ "REMOTE_AGENT_SHARE_UNAVAILABLE": "Model not changed: the shared provider is temporarily unavailable (the owner's computer is offline or sharing is turned off for now). Try again later or pick another model.",+ "SSH_HOST_KEY_MISMATCH": "SSH Host Key Changed"},"providerError": {"AUTH_INVALID": "Invalid or expired API key (401). Check the key and try again",@@ -1145,6 +1146,15 @@"preparingRuntime": "Preparing runtime on {{hostId}}…","installingAgent": "Installing {{agent}} on remote {{hostId}}…","failed": "Failed to install {{agent}} on {{hostId}}: {{message}}. Open Settings → Remote → expand {{hostId}} for the full log."+ },+ "hostKey": {+ "title": "SSH Host Key Changed",+ "review": "Review Host Key",+ "explanation": "The identity key for {{host}} no longer matches the key Cindy saved. Verify the new fingerprint with the server administrator before updating trust.",+ "details": "Previously trusted: {{trusted}}\nNew fingerprint: {{presented}}\n\nA server reinstall or an intercepted connection can cause this change. Compare the new fingerprint through a trusted channel, such as the server console.\n\nCindy’s trust record: {{file}}\nCindy does not read ~/.ssh/known_hosts. Changing your login key or deleting and adding the host will not fix this.\n\nUpdating trust replaces only this host’s fingerprint and reconnects. Other hosts stay unchanged.",+ "cancel": "Keep Existing Key",+ "trust": "Trust New Key and Reconnect",+ "updateFailed": "Could not update host trust. The connection details or saved key may have changed, or the trust file could not be written. Reconnect to refresh the fingerprints and check the file permissions."}},"appearance": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 23091368cc..d29b2b202b 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -735,7 +735,8 @@"PROVIDER_SHARE_CROSS_REGION_DISABLED": "リージョンをまたぐ共有にはまだ対応していません。このリンクは別のリージョンの Cindy サービスのものです。","REMOTE_AGENT_SHARE_PAUSED": "モデルは切り替わっていません:共有した人があなたへの共有を一時停止しました。別のモデルを選んでください。","REMOTE_AGENT_SHARE_REMOVED": "モデルは切り替わっていません:この共有は利用できなくなりました(共有した人が削除したか、あなたが退出しました)。別のモデルを選んでください。",- "REMOTE_AGENT_SHARE_UNAVAILABLE": "モデルは切り替わっていません:共有されたプロバイダーは一時的に利用できません(共有した人のパソコンがオフラインか、共有が一時的にオフになっています)。後でもう一度試すか、別のモデルを選んでください。"+ "REMOTE_AGENT_SHARE_UNAVAILABLE": "モデルは切り替わっていません:共有されたプロバイダーは一時的に利用できません(共有した人のパソコンがオフラインか、共有が一時的にオフになっています)。後でもう一度試すか、別のモデルを選んでください。",+ "SSH_HOST_KEY_MISMATCH": "SSH ホスト鍵が変更されました"},"providerError": {"AUTH_INVALID": "API キーが無効か期限切れです(401)。キーを確認して再試行してください",@@ -1140,6 +1141,15 @@"preparingRuntime": "リモート {{hostId}} のランタイムを準備中…","installingAgent": "リモート {{hostId}} に {{agent}} をインストール中…","failed": "{{hostId}} への {{agent}} インストールに失敗: {{message}}。設定 → リモートマシン → {{hostId}} を展開して完全なログを確認してください。"+ },+ "hostKey": {+ "title": "SSH ホスト鍵が変更されました",+ "review": "ホスト鍵を確認",+ "explanation": "{{host}} のホスト鍵が Cindy に保存された鍵と一致しません。信頼する鍵を更新する前に、サーバー管理者に新しいフィンガープリントを確認してください。",+ "details": "保存済み:{{trusted}}\n新しいフィンガープリント:{{presented}}\n\nサーバーの再インストールや接続先のなりすましが原因の可能性があります。サーバーのコンソールなど、信頼できる経路で新しいフィンガープリントを確認してください。\n\nCindy の信頼記録:{{file}}\nCindy は ~/.ssh/known_hosts を読み取りません。ログイン鍵の変更やホストの削除・再追加では解決しません。\n\n更新すると、このホストのフィンガープリントだけを置き換えて再接続します。他のホストには影響しません。",+ "cancel": "元の鍵を保持",+ "trust": "新しい鍵を信頼して再接続",+ "updateFailed": "ホストの信頼記録を更新できませんでした。接続情報や保存済みの鍵が変更されたか、記録ファイルに書き込めない可能性があります。再接続してフィンガープリントを再取得し、ファイルの権限を確認してください。"}},"appearance": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 21cac70123..a8883358af 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -735,7 +735,8 @@"PROVIDER_SHARE_CROSS_REGION_DISABLED": "다른 지역 간 공유는 아직 지원되지 않습니다. 이 링크는 다른 지역의 Cindy 서비스에서 만든 것입니다.","REMOTE_AGENT_SHARE_PAUSED": "모델이 바뀌지 않았습니다: 공유한 사람이 나에 대한 공유를 일시 중지했습니다. 다른 모델을 선택하세요.","REMOTE_AGENT_SHARE_REMOVED": "모델이 바뀌지 않았습니다: 이 공유는 더 이상 사용할 수 없습니다(공유한 사람이 삭제했거나 내가 나갔습니다). 다른 모델을 선택하세요.",- "REMOTE_AGENT_SHARE_UNAVAILABLE": "모델이 바뀌지 않았습니다: 공유된 제공자를 일시적으로 사용할 수 없습니다(공유한 사람의 컴퓨터가 오프라인이거나 공유가 잠시 꺼져 있습니다). 나중에 다시 시도하거나 다른 모델을 선택하세요."+ "REMOTE_AGENT_SHARE_UNAVAILABLE": "모델이 바뀌지 않았습니다: 공유된 제공자를 일시적으로 사용할 수 없습니다(공유한 사람의 컴퓨터가 오프라인이거나 공유가 잠시 꺼져 있습니다). 나중에 다시 시도하거나 다른 모델을 선택하세요.",+ "SSH_HOST_KEY_MISMATCH": "SSH 호스트 키가 변경됨"},"providerError": {"AUTH_INVALID": "API 키가 유효하지 않거나 만료되었습니다(401). 키를 확인한 후 다시 시도하세요",@@ -1140,6 +1141,15 @@"preparingRuntime": "원격 {{hostId}} 의 런타임 준비 중…","installingAgent": "원격 {{hostId}} 에 {{agent}} 설치 중…","failed": "{{hostId}} 에 {{agent}} 설치 실패: {{message}}。설정 → 원격 머신 → {{hostId}} 확장하여 전체 로그를 확인하세요."+ },+ "hostKey": {+ "title": "SSH 호스트 키가 변경됨",+ "review": "호스트 키 확인",+ "explanation": "{{host}}의 호스트 키가 Cindy에 저장된 키와 일치하지 않습니다. 신뢰할 키를 업데이트하기 전에 서버 관리자에게 새 지문을 확인하세요.",+ "details": "기존 지문: {{trusted}}\n새 지문: {{presented}}\n\n서버 재설치 또는 연결 대상 사칭으로 인해 변경되었을 수 있습니다. 서버 콘솔 등 신뢰할 수 있는 경로로 새 지문을 확인하세요.\n\nCindy 신뢰 기록: {{file}}\nCindy는 ~/.ssh/known_hosts를 읽지 않습니다. 로그인 키를 변경하거나 호스트를 삭제한 뒤 다시 추가해도 해결되지 않습니다.\n\n업데이트하면 이 호스트의 지문만 교체하고 다시 연결합니다. 다른 호스트에는 영향을 주지 않습니다.",+ "cancel": "기존 키 유지",+ "trust": "새 키 신뢰 및 다시 연결",+ "updateFailed": "호스트 신뢰 기록을 업데이트할 수 없습니다. 연결 정보나 저장된 키가 변경되었거나 기록 파일에 쓸 수 없을 수 있습니다. 다시 연결하여 지문을 새로 확인하고 파일 권한을 확인하세요."}},"appearance": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 3bd5d65d08..65e2fd0c9c 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -735,7 +735,8 @@"PROVIDER_SHARE_CROSS_REGION_DISABLED": "暂不支持跨区域分享。这个链接来自另一个区域的 Cindy 服务。","REMOTE_AGENT_SHARE_PAUSED": "模型未切换:对方已暂停对你的分享。请换一个模型。","REMOTE_AGENT_SHARE_REMOVED": "模型未切换:这个分享已不可用(对方删除了分享或你已退出)。请换一个模型。",- "REMOTE_AGENT_SHARE_UNAVAILABLE": "模型未切换:分享的供应商暂时不可用(对方电脑不在线,或对方暂时关闭了分享)。请稍后再试或换一个模型。"+ "REMOTE_AGENT_SHARE_UNAVAILABLE": "模型未切换:分享的供应商暂时不可用(对方电脑不在线,或对方暂时关闭了分享)。请稍后再试或换一个模型。",+ "SSH_HOST_KEY_MISMATCH": "SSH 主机密钥已变化"},"providerError": {"AUTH_INVALID": "API 密钥无效或已过期(401),请检查密钥后重试",@@ -1140,6 +1141,15 @@"preparingRuntime": "正在为远端 {{hostId}} 准备运行时…","installingAgent": "正在远端 {{hostId}} 安装 {{agent}}…","failed": "远端 {{hostId}} 安装 {{agent}} 失败:{{message}}。请到 设置 → 远端机器 → 展开 {{hostId}} 查看完整日志。"+ },+ "hostKey": {+ "title": "SSH 主机密钥已变化",+ "review": "核对主机密钥",+ "explanation": "{{host}} 的身份密钥与 Cindy 保存的记录不一致。请先向服务器管理员核实新指纹,再更新信任记录。",+ "details": "原指纹:{{trusted}}\n新指纹:{{presented}}\n\n服务器重装或连接被冒充都可能导致这一变化。请通过服务器控制台等可信渠道核对新指纹。\n\nCindy 信任记录:{{file}}\nCindy 不读取 ~/.ssh/known_hosts。更换登录密钥或删除后重新添加主机都无法解决此问题。\n\n更新信任后,仅替换这台主机的指纹并重新连接,不影响其他主机。",+ "cancel": "保留原密钥",+ "trust": "信任新密钥并重连",+ "updateFailed": "无法更新主机信任记录。连接信息或已存密钥可能已变化,也可能无法写入记录文件。请重新连接以刷新指纹,并检查文件权限"}},"appearance": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 6e69aeafc4..22a273d3b8 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -735,7 +735,8 @@"PROVIDER_SHARE_CROSS_REGION_DISABLED": "暫不支援跨區域分享。這個連結來自另一個區域的 Cindy 服務。","REMOTE_AGENT_SHARE_PAUSED": "模型未切換:對方已暫停對你的分享。請換一個模型。","REMOTE_AGENT_SHARE_REMOVED": "模型未切換:這個分享已無法使用(對方刪除了分享或你已退出)。請換一個模型。",- "REMOTE_AGENT_SHARE_UNAVAILABLE": "模型未切換:分享的供應商暫時無法使用(對方電腦不在線,或對方暫時關閉了分享)。請稍後再試或換一個模型。"+ "REMOTE_AGENT_SHARE_UNAVAILABLE": "模型未切換:分享的供應商暫時無法使用(對方電腦不在線,或對方暫時關閉了分享)。請稍後再試或換一個模型。",+ "SSH_HOST_KEY_MISMATCH": "SSH 主機金鑰已變更"},"providerError": {"AUTH_INVALID": "API 金鑰無效或已過期(401),請檢查金鑰後重試",@@ -1140,6 +1141,15 @@"preparingRuntime": "正在為遠端 {{hostId}} 準備執行時…","installingAgent": "正在遠端 {{hostId}} 安裝 {{agent}}…","failed": "遠端 {{hostId}} 安裝 {{agent}} 失敗:{{message}}。請到 設定 → 遠端機器 → 展開 {{hostId}} 檢視完整日誌。"+ },+ "hostKey": {+ "title": "SSH 主機金鑰已變更",+ "review": "核對主機金鑰",+ "explanation": "{{host}} 的身分金鑰與 Cindy 儲存的記錄不一致。請先向伺服器管理員核實新指紋,再更新信任記錄。",+ "details": "原指紋:{{trusted}}\n新指紋:{{presented}}\n\n伺服器重裝或連線遭冒充都可能導致此變更。請透過伺服器主控台等可信管道核對新指紋。\n\nCindy 信任記錄:{{file}}\nCindy 不讀取 ~/.ssh/known_hosts。更換登入金鑰或刪除後重新新增主機都無法解決此問題。\n\n更新信任後,只替換這台主機的指紋並重新連線,不影響其他主機。",+ "cancel": "保留原金鑰",+ "trust": "信任新金鑰並重新連線",+ "updateFailed": "無法更新主機信任記錄。連線資訊或已存金鑰可能已變更,也可能無法寫入記錄檔。請重新連線以更新指紋,並檢查檔案權限"}},"appearance": {diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 9b2e68f7d8..6cda44f283 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -103,6 +103,7 @@ type RemoteHostSnapshot = {};status: import('@cindy/maker-remote-ssh').RemoteStatus;lastError?: string;+ hostKeyMismatch?: import('@cindy/maker-remote-ssh').HostSnapshot['hostKeyMismatch'];lastAuthLabel?: string;statusChangedAt: number;autoConnect: boolean;@@ -4129,6 +4130,7 @@ interface ElectronAPI {agentProxy?: AgentProxyPrefPayload | null;}) => Promise<{ host: RemoteHostSnapshot }>;remove: (id: string) => Promise<{ ok: true }>;+ reviewHostKey: (id: string) => Promise<{ updated: boolean }>;connect: (id: string) => Promise<{ host: RemoteHostSnapshot | null }>;disconnect: (id: string) => Promise<{ host: RemoteHostSnapshot | null }>;onStatusChanged: (cb: (snap: RemoteHostSnapshot) => void) => () => void;diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex 162a91e738..21e42b7b8e 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -185,6 +185,7 @@ export type IpcErrorCode =| 'LEARN_BUSY' // 已有 learn run 在进行(全局并发 1)| 'LEARN_INVALID_STATE' // run 状态不允许该操作(如对非 awaiting-review 调 apply)// remote-ssh:连接阶段+ | 'SSH_HOST_KEY_MISMATCH'| 'SSH_CONNECT_FAILED'| 'SSH_AUTH_FAILED'| 'SSH_CONFIG_IO_FAILED'@@ -410,6 +411,7 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['GOAL_NOT_FOUND','LEARN_BUSY','LEARN_INVALID_STATE',+ 'SSH_HOST_KEY_MISMATCH','SSH_CONNECT_FAILED','SSH_AUTH_FAILED','SSH_CONFIG_IO_FAILED',diff --git a/packages/maker-remote-ssh/src/RemoteHost.ts b/packages/maker-remote-ssh/src/RemoteHost.tsindex f574162a08..760871866c 100644--- a/packages/maker-remote-ssh/src/RemoteHost.ts+++ b/packages/maker-remote-ssh/src/RemoteHost.ts@@ -369,6 +369,7 @@ export class RemoteHost {* Reset at the start of every connect attempt.*/private hostKeyError: string | null = null;+ private hostKeyMismatch: HostSnapshot['hostKeyMismatch'];/*** 已登记的 remote forwarding 愿望清单 (key = localHost:localPort)。* 连接断开不清空 — 重连成功后 doConnect 会逐个 re-arm, 尽量绑回原端口。@@ -404,6 +405,7 @@ export class RemoteHost {if (next.id !== this.cfg.id) {throw new Error(`RemoteHost.updateConfig: id mismatch (${next.id} != ${this.cfg.id})`);}+ this.hostKeyMismatch = undefined;this.cfg = next;this.events.emit('status', this.snapshot());}@@ -413,6 +415,7 @@ export class RemoteHost {config: this.cfg,status: this.status,lastError: this.lastError,+ hostKeyMismatch: this.hostKeyMismatch ? { ...this.hostKeyMismatch } : undefined,lastAuthLabel: this.lastAuthLabel,statusChangedAt: this.statusChangedAt,};@@ -1159,11 +1162,14 @@ export class RemoteHost {}// mismatchif (isCurrentAttempt()) {+ this.hostKeyMismatch = { host: storeKey, trusted: stored!, presented };this.hostKeyError =- `Remote host key for ${storeKey} changed (${presented}) and no longer matches the ` +- `previously trusted key. This can mean the server was reinstalled — or a ` +- `man-in-the-middle. Connection refused. If you trust the change, remove the stale ` +- `entry from maker's known hosts and reconnect.`;+ `SSH host key changed for ${storeKey}. Connection refused.\n` ++ `Previously trusted: ${stored}\nPresented: ${presented}\n` ++ `This may be a server reinstall or an intercepted connection. Verify the new fingerprint ` ++ `with the server administrator through a trusted channel, then review the host key in ` ++ `Cindy Settings > Remote. Cindy uses its own remote-ssh/known-hosts.json, not ` ++ `~/.ssh/known_hosts. Changing your login key will not fix this error.`;}this.log.error('ssh host key mismatch — refusing connect', {id: this.id,@@ -1200,6 +1206,7 @@ export class RemoteHost {};this.setStatus('connecting');this.hostKeyError = null;+ this.hostKeyMismatch = undefined;this.lastAuthError = null;let auth;@@ -1309,6 +1316,7 @@ export class RemoteHost {// Reject with the friendly message so IPC layer's toast also gets// the actionable copy (it pulls from `.message`).const rejectErr = new Error(this.lastError);+ if (this.hostKeyMismatch) Object.assign(rejectErr, { code: 'SSH_HOST_KEY_MISMATCH' });// Preserve original for tests / debugging that key off message text.(rejectErr as Error & { cause?: unknown }).cause = err;reject(rejectErr);@@ -1381,6 +1389,11 @@ export class RemoteHost {this.setStatus('disconnected');return;}+ if (this.hostKeyError) {+ this.clearReconnectTimer();+ this.setStatus('failed');+ return;+ }// Auth failures are deterministic — retrying with the same agent / key// produces the same outcome. Fail fast so the user sees the actionable// hint immediately instead of waiting 30+ s for the backoff to give up.@@ -1419,7 +1432,7 @@ export class RemoteHost {void this.startConnectAttempt().catch((err) => {// doConnect already set status=failed and recorded lastError.// If we still have attempts left, schedule again.- if (this.userDisconnected) return;+ if (this.userDisconnected || this.hostKeyError) return;if (this.reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {this.scheduleReconnect();} else {diff --git a/packages/maker-remote-ssh/src/__tests__/hostKeys.test.ts b/packages/maker-remote-ssh/src/__tests__/hostKeys.test.tsindex b72049336a..323e787b2f 100644--- a/packages/maker-remote-ssh/src/__tests__/hostKeys.test.ts+++ b/packages/maker-remote-ssh/src/__tests__/hostKeys.test.ts@@ -16,7 +16,7 @@import { promises as fs } from 'node:fs';import os from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {FileHostKeyStore,@@ -78,9 +78,115 @@ describe('FileHostKeyStore', () => {});afterEach(async () => {+ vi.restoreAllMocks();await fs.rm(scratchDir, { recursive: true, force: true });});+ it('replaces only the reviewed fingerprint and survives reopening', async () => {+ const store = new FileHostKeyStore(filePath);+ await store.set('one:22', 'SHA256:old');+ await store.set('two:22', 'SHA256:other');+ await store.replace('one:22', 'SHA256:old', 'SHA256:new', () => true);+ const reopened = new FileHostKeyStore(filePath);+ expect(await reopened.get('one:22')).toBe('SHA256:new');+ expect(await reopened.get('two:22')).toBe('SHA256:other');+ await expect(store.set('one:22', 'SHA256:unreviewed')).rejects.toThrow();+ });++ it('preserves trust when confirmation expires while the temporary file is written', async () => {+ const store = new FileHostKeyStore(filePath);+ await store.set('one:22', 'SHA256:old');+ await store.set('two:22', 'SHA256:other');+ let current = true;+ const writeFile = fs.writeFile.bind(fs);+ vi.spyOn(fs, 'writeFile').mockImplementationOnce(async (...args) => {+ await writeFile(...args);+ current = false;+ });++ await expect(store.replace('one:22', 'SHA256:old', 'SHA256:new', () => current))+ .rejects.toThrow('Host key details changed');+ expect(await store.get('one:22')).toBe('SHA256:old');+ expect(JSON.parse(await fs.readFile(filePath, 'utf8'))).toEqual({+ 'one:22': 'SHA256:old', 'two:22': 'SHA256:other',+ });+ expect(await fs.readdir(path.dirname(filePath))).toEqual(['known-hosts.json']);+ await store.replace('one:22', 'SHA256:old', 'SHA256:reviewed-again', () => true);+ expect(await new FileHostKeyStore(filePath).get('one:22')).toBe('SHA256:reviewed-again');+ });++ it('keeps concurrent reads and first-use writes behind a pending trust replacement', async () => {+ const store = new FileHostKeyStore(filePath);+ await store.set('one:22', 'SHA256:old');+ let releaseWrite!: () => void;+ let writing!: () => void;+ const blocked = new Promise<void>(resolve => { releaseWrite = resolve; });+ const entered = new Promise<void>(resolve => { writing = resolve; });+ const writeFile = fs.writeFile.bind(fs);+ vi.spyOn(fs, 'writeFile').mockImplementationOnce(async (...args) => {+ await writeFile(...args);+ writing();+ await blocked;+ });+ const replacing = store.replace('one:22', 'SHA256:old', 'SHA256:new', () => true);+ await entered;+ const readFile = fs.readFile.bind(fs);+ let releaseRead!: () => void;+ const readBlocked = new Promise<void>(resolve => { releaseRead = resolve; });+ const read = vi.spyOn(fs, 'readFile').mockImplementation(async (...args) => {+ const value = await readFile(...args);+ await readBlocked;+ return value;+ });+ store.reload();+ const concurrentRead = store.get('one:22');+ const firstUse = store.get('two:22').then(value => {+ expect(value).toBeNull();+ return store.set('two:22', 'SHA256:other');+ });+ // Let pending microtasks run while persistence is deliberately suspended.+ await new Promise<void>(resolve => setImmediate(resolve));+ const readsDuringWrite = read.mock.calls.length;+ releaseWrite();+ await replacing;+ releaseRead();+ const observed = await concurrentRead;+ await firstUse;+ expect(await store.get('one:22')).toBe('SHA256:new');+ const reopened = new FileHostKeyStore(filePath);+ expect(await reopened.get('one:22')).toBe('SHA256:new');+ expect(await reopened.get('two:22')).toBe('SHA256:other');+ expect(readsDuringWrite).toBe(0);+ expect(observed).toBe('SHA256:new');+ });++ it('rejects stale confirmations, removed entries, and concurrent replacements', async () => {+ const store = new FileHostKeyStore(filePath);+ await store.set('one:22', 'SHA256:old');+ await expect(store.replace('one:22', 'SHA256:old', 'SHA256:new', () => false)).rejects.toThrow();+ expect(await store.get('one:22')).toBe('SHA256:old');+ await expect(store.replace('missing:22', 'SHA256:old', 'SHA256:new', () => true)).rejects.toThrow();+ const results = await Promise.allSettled([+ store.replace('one:22', 'SHA256:old', 'SHA256:new', () => true),+ store.replace('one:22', 'SHA256:old', 'SHA256:other', () => true),+ ]);+ expect(results.map((result) => result.status)).toEqual(['fulfilled', 'rejected']);+ expect(await store.get('one:22')).toBe('SHA256:new');+ });++ it('rereads manual repairs and retains old trust when replacement cannot be saved', async () => {+ const store = new FileHostKeyStore(filePath);+ await store.set('one:22', 'SHA256:old');+ await fs.writeFile(filePath, JSON.stringify({ 'one:22': 'SHA256:manual' }));+ await expect(store.replace('one:22', 'SHA256:old', 'SHA256:new', () => true)).rejects.toThrow();+ expect(await store.get('one:22')).toBe('SHA256:manual');+ const blocker = `${filePath}.${process.pid}.tmp`;+ await fs.mkdir(blocker);+ await expect(store.replace('one:22', 'SHA256:manual', 'SHA256:new', () => true)).rejects.toThrow();+ expect(await store.get('one:22')).toBe('SHA256:manual');+ expect(await new FileHostKeyStore(filePath).get('one:22')).toBe('SHA256:manual');+ });+it('returns null for an unknown host', async () => {const store = new FileHostKeyStore(filePath);expect(await store.get('example.com:22')).toBeNull();diff --git a/packages/maker-remote-ssh/src/__tests__/remoteHostConnectRace.test.ts b/packages/maker-remote-ssh/src/__tests__/remoteHostConnectRace.test.tsindex c0521987d3..51031a6602 100644--- a/packages/maker-remote-ssh/src/__tests__/remoteHostConnectRace.test.ts+++ b/packages/maker-remote-ssh/src/__tests__/remoteHostConnectRace.test.ts@@ -198,6 +198,60 @@ describe('RemoteHost arm/disconnect race', () => {expect(host.getStatus()).toBe('disconnected');});+ it('reports locally verified key changes and clears recovery on endpoint change', async () => {+ const store: HostKeyStore = {+ reload: vi.fn(), get: vi.fn(async () => 'SHA256:trusted'), set: vi.fn(),+ };+ const host = new RemoteHost(HOST_CONFIG, { logger: noopLogger, hostKeys: store });+ const connecting = host.connect();+ const rejection = expect(connecting).rejects.toThrow('SSH host key changed');+ await flush();+ const client = h.client!;+ const accepted = await new Promise<boolean>((resolve) => {+ client.connectConfig!.hostVerifier!(Buffer.from('replacement-key'), resolve);+ });+ expect(accepted).toBe(false);+ client.emit('error', new Error('Host denied (verification failed)'));+ await rejection;+ expect(host.snapshot().hostKeyMismatch).toEqual({+ host: `${HOST_CONFIG.hostname}:${HOST_CONFIG.port}`,+ trusted: 'SHA256:trusted', presented: expect.stringMatching(/^SHA256:/),+ });+ expect(host.snapshot().lastError).toContain('~/.ssh/known_hosts');+ expect(store.set).not.toHaveBeenCalled();+ client.emit('close');+ expect(host.getStatus()).toBe('failed');+ host.updateConfig({ ...HOST_CONFIG, hostname: 'changed.example' });+ expect(host.snapshot().hostKeyMismatch).toBeUndefined();+ await host.disconnect();+ });++ it('stops a scheduled reconnect when the server key has changed', async () => {+ const store: HostKeyStore = { reload: vi.fn(), get: vi.fn(async () => 'SHA256:old'), set: vi.fn() };+ const host = new RemoteHost(HOST_CONFIG, { logger: noopLogger, hostKeys: store });+ const connecting = host.connect();+ await flush();+ h.client!.emit('ready');+ await connecting;+ vi.useFakeTimers();+ try {+ h.client!.emit('close');+ expect(host.getStatus()).toBe('reconnecting');+ await vi.advanceTimersByTimeAsync(1000);+ const client = h.client!;+ await new Promise<boolean>((resolve) => client.connectConfig!.hostVerifier!(Buffer.from('new-key'), resolve));+ client.emit('error', new Error('Host denied (verification failed)'));+ client.emit('close');+ await vi.advanceTimersByTimeAsync(60_000);+ expect(host.getStatus()).toBe('failed');+ expect(h.client).toBe(client);+ expect(host.snapshot().hostKeyMismatch).toBeDefined();+ } finally {+ await host.disconnect();+ vi.useRealTimers();+ }+ });+it('a stale host verifier cannot persist trust or write errors for a replacement endpoint', async () => {let finishGet!: (fingerprint: string | null) => void;const store: HostKeyStore = {diff --git a/packages/maker-remote-ssh/src/hostKeys.ts b/packages/maker-remote-ssh/src/hostKeys.tsindex 5dba77b188..101842fad6 100644--- a/packages/maker-remote-ssh/src/hostKeys.ts+++ b/packages/maker-remote-ssh/src/hostKeys.ts@@ -78,10 +78,11 @@ export function decideHostKey(stored: string | null, presented: string): HostKey* 0600 (best-effort; chmod is a no-op on Windows).*/export class FileHostKeyStore implements HostKeyStore {- private readonly filePath: string;+ readonly filePath: string;private cache: Record<string, string> | null = null;private loadPromise: Promise<Record<string, string>> | null = null;private loadSettled = false; // true once loadPromise has resolved or rejected+ // Reads share the write queue so an older disk load cannot overwrite a committed cache.private writeChain: Promise<void> = Promise.resolve();constructor(filePath: string) {@@ -89,8 +90,13 @@ export class FileHostKeyStore implements HostKeyStore {}async get(key: string): Promise<string | null> {- const map = await this.load();- return map[key] ?? null;+ const slot = this.writeChain.catch(() => {}).then(async () => {+ const map = await this.load();+ return map[key] ?? null;+ });+ // Keep failures observable to this caller without poisoning subsequent operations.+ this.writeChain = slot.then(() => undefined, () => undefined);+ return slot;}reload(): void {@@ -139,6 +145,24 @@ export class FileHostKeyStore implements HostKeyStore {await mySlot;}+ /** Replace only the fingerprint the user reviewed; never reset trust to first-use. */+ async replace(key: string, expected: string, fingerprint: string, isCurrent: () => boolean): Promise<void> {+ const slot = this.writeChain.catch(() => {}).then(async () => {+ this.reload();+ const map = await this.load();+ if (!isCurrent() || map[key] !== expected) {+ throw new Error('Host key details changed. Reconnect and review the current fingerprints.');+ }+ const next = { ...map, [key]: fingerprint };+ await this.persist(next, isCurrent);+ // Publish only after persistence succeeds, leaving the old trust on failure.+ this.cache = next;+ this.loadPromise = null;+ });+ this.writeChain = slot;+ await slot;+ }+/*** Load the map once. Concurrent callers share a single in-flight read so* they end up mutating the same cached object — otherwise simultaneous@@ -188,11 +212,19 @@ export class FileHostKeyStore implements HostKeyStore {return this.loadPromise;}- private async persist(map: Record<string, string>): Promise<void> {+ private async persist(map: Record<string, string>, isCurrent?: () => boolean): Promise<void> {await fs.mkdir(path.dirname(this.filePath), { recursive: true });const tmp = `${this.filePath}.${process.pid}.tmp`;- await fs.writeFile(tmp, JSON.stringify(map, null, 2), { mode: 0o600 });- await fs.rename(tmp, this.filePath);+ try {+ await fs.writeFile(tmp, JSON.stringify(map, null, 2), { mode: 0o600 });+ // Writing the temporary file yields; the reviewed host may have changed meanwhile.+ if (isCurrent && !isCurrent()) {+ throw new Error('Host key details changed. Reconnect and review the current fingerprints.');+ }+ await fs.rename(tmp, this.filePath);+ } finally {+ await fs.rm(tmp, { force: true }).catch(() => undefined);+ }// Enforce mode even if the file pre-existed with looser perms.await fs.chmod(this.filePath, 0o600).catch(() => undefined);}diff --git a/packages/maker-remote-ssh/src/types.ts b/packages/maker-remote-ssh/src/types.tsindex 2401addf65..5322a7843a 100644--- a/packages/maker-remote-ssh/src/types.ts+++ b/packages/maker-remote-ssh/src/types.ts@@ -72,11 +72,19 @@ export interface HostConfig {managedByCindy: boolean;}+/** Local verification result; never inferred from server-provided error text. */+export interface HostKeyMismatch {+ host: string;+ trusted: string;+ presented: string;+}+/** Snapshot of a host's runtime state for renderer. */export interface HostSnapshot {config: HostConfig;status: RemoteStatus;lastError?: string;+ hostKeyMismatch?: HostKeyMismatch;/*** Human-readable label for the credential that succeeded on the most* recent connect — e.g. "ssh-agent" or "key:id_ed25519". Undefined when