Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(remote-ssh): align OpenSSH discovery and authentication (#3213)

洪朔73af3756b653
diff --git a/apps/desktop/src/main/file-browser/__tests__/remoteFileBrowser.test.ts b/apps/desktop/src/main/file-browser/__tests__/remoteFileBrowser.test.ts
index d83175059f..be08da25c6 100644
--- a/apps/desktop/src/main/file-browser/__tests__/remoteFileBrowser.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/remoteFileBrowser.test.ts
@@ -218,4 +218,20 @@ describe('RemoteFileBrowserManager', () => {
expect(calls.spawn).toBe(2);
await mgr.disposeAll();
});
+
+ it('endpoint invalidation fences an in-flight build before it can spawn the old host', async () => {
+ let releaseEnsure!: () => void;
+ const { deps, calls } = makeDeps({ probeResults: [READY_PROBE] });
+ deps.ensureHostReady = () => new Promise<void>((resolve) => {
+ releaseEnsure = resolve;
+ });
+ const mgr = new RemoteFileBrowserManager(deps);
+ const request = mgr.request('h1', 'listDir', { workdir });
+
+ await mgr.disposeHost('h1');
+ releaseEnsure();
+
+ await expect(request).rejects.toMatchObject({ code: 'ENDPOINT_STALE' });
+ expect(calls.spawn).toBe(0);
+ });
});
diff --git a/apps/desktop/src/main/file-browser/remote-deps.ts b/apps/desktop/src/main/file-browser/remote-deps.ts
index 6a31416de6..a414dd0a79 100644
--- a/apps/desktop/src/main/file-browser/remote-deps.ts
+++ b/apps/desktop/src/main/file-browser/remote-deps.ts
@@ -15,7 +15,11 @@ import {
} from '@cindy/maker-remote-ssh';
import { createLogger } from '../logger.js';
-import { ensureRemoteHostReady, getRemoteSshPool } from '../remote-ssh/index.js';
+import {
+ ensureRemoteHostReady,
+ getRemoteSshPool,
+ setRemoteFileBrowserEndpointInvalidator,
+} from '../remote-ssh/index.js';
import { RemoteFileBrowserManager } from './remote.js';
const log = createLogger('file-browser/remote-deps');
@@ -47,6 +51,10 @@ export function resolveFileServiceBundlePath(): string {
let manager: RemoteFileBrowserManager | null = null;
+setRemoteFileBrowserEndpointInvalidator(async (hostId) => {
+ if (manager) await manager.disposeHost(hostId);
+});
+
/** 生产单例。首次调用装配真实依赖。 */
export function getRemoteFileBrowser(): RemoteFileBrowserManager {
if (manager) return manager;
diff --git a/apps/desktop/src/main/file-browser/remote.ts b/apps/desktop/src/main/file-browser/remote.ts
index 9522ed50f3..4ae45960f0 100644
--- a/apps/desktop/src/main/file-browser/remote.ts
+++ b/apps/desktop/src/main/file-browser/remote.ts
@@ -86,6 +86,8 @@ export class RemoteFileBrowserManager {
private readonly log: Logger;
/** in-flight 或已就绪的 client(promise 形态做并发去重)。 */
private readonly clients = new Map<string, Promise<FileServiceClient>>();
+ /** Per-alias fence preventing stale endpoint builds from publishing. */
+ private readonly endpointGenerations = new Map<string, number>();
/**
* per-host 事件订阅者(搜索流 / P4 watch)。生命周期独立于 client——client
* 断链重建后 buildClient 会重新挂一个转发器,订阅者无感。
@@ -99,6 +101,23 @@ export class RemoteFileBrowserManager {
this.log = deps.logger ?? log;
}
+ private currentEndpointGeneration(hostId: string): number {
+ return this.endpointGenerations.get(hostId) ?? 0;
+ }
+
+ private advanceEndpointGeneration(hostId: string): void {
+ this.endpointGenerations.set(hostId, this.currentEndpointGeneration(hostId) + 1);
+ }
+
+ private assertCurrentEndpointGeneration(hostId: string, generation: number): void {
+ if (this.currentEndpointGeneration(hostId) !== generation) {
+ throw new FileServiceRpcError(
+ 'ENDPOINT_STALE',
+ `remote file-service endpoint changed while work was in flight: ${hostId}`,
+ );
+ }
+ }
+
/**
* 类型安全的远程调用入口。断链自动重建一次(仅幂等读方法);其余错误原样抛
* FileServiceRpcError(caller 决定 throwIpcError 还是 {ok:false})。
@@ -108,10 +127,15 @@ export class RemoteFileBrowserManager {
method: M,
params: FsRpcMethods[M]['params'],
): Promise<FsRpcMethods[M]['result']> {
- const client = await this.getClient(hostId);
+ const generation = this.currentEndpointGeneration(hostId);
+ const client = await this.getClient(hostId, generation);
+ this.assertCurrentEndpointGeneration(hostId, generation);
try {
- return await client.request(method, params);
+ const result = await client.request(method, params);
+ this.assertCurrentEndpointGeneration(hostId, generation);
+ return result;
} catch (err) {
+ this.assertCurrentEndpointGeneration(hostId, generation);
const code = (err as FileServiceRpcError)?.code;
if (
(code === 'CHANNEL_CLOSED' || code === 'CHANNEL_ERROR') &&
@@ -123,8 +147,10 @@ export class RemoteFileBrowserManager {
// 伪失败;变更类断链一律把错误交回调用方由用户决定重试。
this.log.warn('file-service channel lost, rebuilding', { hostId, method });
this.clients.delete(hostId);
- const rebuilt = await this.getClient(hostId);
- return await rebuilt.request(method, params);
+ const rebuilt = await this.getClient(hostId, generation);
+ const result = await rebuilt.request(method, params);
+ this.assertCurrentEndpointGeneration(hostId, generation);
+ return result;
}
if (code === 'CHANNEL_CLOSED' || code === 'CHANNEL_ERROR') {
// 变更类断链仍要重建 client,让下一次调用可用;本次错误如实上抛。
@@ -170,14 +196,14 @@ export class RemoteFileBrowserManager {
/** 主动断开某 host 的 client(host 断开 / 应用退出清理)。幂等。 */
async disposeHost(hostId: string): Promise<void> {
+ this.advanceEndpointGeneration(hostId);
const pending = this.clients.get(hostId);
if (!pending) return;
this.clients.delete(hostId);
- try {
- (await pending).dispose();
- } catch {
- // 建链失败的 promise——无资源可清
- }
+ // Do not await an in-flight build: it may be blocked on readiness. The
+ // generation fence makes it fail before publishing, then this continuation
+ // disposes any client it managed to construct.
+ void pending.then((client) => client.dispose()).catch(() => undefined);
}
async disposeAll(): Promise<void> {
@@ -185,17 +211,18 @@ export class RemoteFileBrowserManager {
await Promise.allSettled(ids.map((id) => this.disposeHost(id)));
}
- private getClient(hostId: string): Promise<FileServiceClient> {
+ private getClient(hostId: string, generation: number): Promise<FileServiceClient> {
const existing = this.clients.get(hostId);
if (existing) {
// 已有 in-flight 或活 client;死 client 在 await 后甄别并重建。
return existing.then((c) => {
+ this.assertCurrentEndpointGeneration(hostId, generation);
if (!c.isDead) return c;
if (this.clients.get(hostId) === existing) this.clients.delete(hostId);
- return this.getClient(hostId);
+ return this.getClient(hostId, generation);
});
}
- const building = this.buildClient(hostId);
+ const building = this.buildClient(hostId, generation);
this.clients.set(hostId, building);
building.catch(() => {
// 建链失败不留缓存,下次请求重走全链。
@@ -205,10 +232,12 @@ export class RemoteFileBrowserManager {
}
/** 完整就绪链:连接 → probe → 需要则装 → 启 daemon → handshake。 */
- private async buildClient(hostId: string): Promise<FileServiceClient> {
+ private async buildClient(hostId: string, generation: number): Promise<FileServiceClient> {
await this.deps.ensureHostReady(hostId);
+ this.assertCurrentEndpointGeneration(hostId, generation);
let probe = await this.deps.probe(hostId);
+ this.assertCurrentEndpointGeneration(hostId, generation);
// bundleVersion 也参与比较:schema 兼容的 daemon 行为修复(如新增错误码)
// 只 bump bundle 版本,不比它就永远不会重推,修复会静默发不出去。
const needsInstall =
@@ -233,20 +262,30 @@ export class RemoteFileBrowserManager {
localBundle: FILE_SERVICE_BUNDLE_VERSION,
});
const r = await this.deps.install(hostId);
+ this.assertCurrentEndpointGeneration(hostId, generation);
if (!r.ready) {
throw new FileServiceRpcError('INSTALL_FAILED', r.error ?? 'file-service install failed');
}
probe = await this.deps.probe(hostId);
+ this.assertCurrentEndpointGeneration(hostId, generation);
}
+ this.assertCurrentEndpointGeneration(hostId, generation);
const host = this.deps.getHost(hostId);
const rgArg = probe.rgPath ? ` --rg ${shq(probe.rgPath)}` : '';
const stream = await host.execStream(
`${shq(probe.nodeBinaryPath)} ${shq(probe.binaryPath)}${rgArg}`,
);
+ try {
+ this.assertCurrentEndpointGeneration(hostId, generation);
+ } catch (err) {
+ try { stream.kill(); } catch { /* best effort */ }
+ throw err;
+ }
const client = new FileServiceClient({ stream, logger: this.log });
try {
const info = await client.connect();
+ this.assertCurrentEndpointGeneration(hostId, generation);
this.log.info('file-service connected', { hostId, ...info });
// 事件转发:daemon event 帧 → 该 host 的所有订阅者。挂在 client 上,
// client 死亡自动清;重建时这里重新挂,订阅者(hostListeners)无感。
@@ -274,7 +313,9 @@ export class RemoteFileBrowserManager {
// (bundle 半新半旧的罕见态)——重推后由 caller 的下一次请求重走建链。
if ((err as FileServiceRpcError)?.code === 'SCHEMA_MISMATCH') {
this.log.warn('handshake schema mismatch, forcing reinstall', { hostId });
+ this.assertCurrentEndpointGeneration(hostId, generation);
await this.deps.install(hostId);
+ this.assertCurrentEndpointGeneration(hostId, generation);
}
throw err;
}
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index b844ddf929..6d925d7cce 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -7,6 +7,7 @@ import {
type LiziMcpProvider,
type LiziMcpSessionContext,
type LspServerPool,
+ type SshHostSnapshotLike,
} from '@cindy/mcps';
import type { OrcaMcpDeps } from '@cindy/mcps';
import { createCindyGhostsMcpServer } from 'cindy-tools';
@@ -94,6 +95,13 @@ export interface DesktopMcpProvidersDeps {
export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcpProvider[] {
const { pluginRegistry } = deps;
+ let redactSshText: ((snapshot: SshHostSnapshotLike, text: string) => string) | undefined;
+ const loadRemoteSsh = async () => {
+ const remoteSsh = await import('../remote-ssh/index.js');
+ redactSshText = (snapshot, text) =>
+ remoteSsh.redactSshSensitiveText(snapshot.config, text);
+ return remoteSsh;
+ };
// 辅助桥接 OrcaCollabService → OrcaMcpDeps / sendToSession,
// 并在边界捕获 HOST_NOT_READY / INTERNAL。
@@ -276,9 +284,13 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
// hydrated accessor:冷启动时 pool 是空的(hydrate 只在用户访问设置或
// connect 路径触发),ssh_list_hosts / resolveHost 读 pool.list() 前必须
// 先从 ~/.ssh/config hydrate,否则已配置主机全部 HOST_NOT_FOUND。
- getPool: async () => (await import('../remote-ssh/index.js')).getRemoteSshPoolHydrated(),
+ getPool: async () => (await loadRemoteSsh()).getRemoteSshPoolHydrated(),
ensureReady: async (id: string) =>
- (await import('../remote-ssh/index.js')).ensureRemoteHostReady(id),
+ (await loadRemoteSsh()).ensureRemoteHostReady(id),
+ redactSensitiveText: (snapshot, text) => {
+ if (!redactSshText) throw new Error('SSH redactor is not initialized');
+ return redactSshText(snapshot, text);
+ },
// 普通工具策略在 Claude runtime / Codex thread 创建时冻结。不要在 tool-call
// 时重新读取 registry,否则运行中的工具清单与执行权限会随 Settings 分叉。
logger: createLogger('mcp/cindy_ssh'),
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts
index 5adaba4b4d..8cda25cbde 100644
--- a/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts
+++ b/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts
@@ -63,8 +63,10 @@ import {
import {
getSshHostAgentProxy,
getSshHostAutoConnect,
+ getSshHostDisplayName,
setSshHostAgentProxy,
setSshHostAutoConnect,
+ setSshHostDisplayName,
type SshHostAgentProxyPref,
} from '../ssh-host-prefs-store';
@@ -89,6 +91,7 @@ function makeFakeHost(opts: { marker?: string | null } = {}) {
user: 'deploy',
authMethod: 'agent',
source: 'manual',
+ managedByCindy: false,
},
getStatus: () => 'ready',
async exec(cmd: string, execOpts?: { input?: string }) {
@@ -144,6 +147,17 @@ describe('resolveAgentProxyUrl', () => {
});
});
+describe('SSH host display name preference', () => {
+ it('round-trips independently from connection fields and falls back to alias', () => {
+ expect(getSshHostDisplayName('test-host')).toBe('test-host');
+ setSshHostDisplayName('test-host', 'Build box');
+ expect(getSshHostDisplayName('test-host')).toBe('Build box');
+ expect(JSON.parse(prefsFileContent ?? '{}')['test-host']).toMatchObject({
+ displayName: 'Build box',
+ });
+ });
+});
+
describe('buildAgentProxyEnv', () => {
it('builds dual-case proxy env pointing at the proxy URL', () => {
const env = buildAgentProxyEnv('http://127.0.0.1:17893');
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/agentProxyTunnel.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/agentProxyTunnel.test.ts
index 760f5907c7..02407218f2 100644
--- a/apps/desktop/src/main/remote-ssh/__tests__/agentProxyTunnel.test.ts
+++ b/apps/desktop/src/main/remote-ssh/__tests__/agentProxyTunnel.test.ts
@@ -13,6 +13,7 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import type { HostConfig } from '@cindy/maker-remote-ssh';
import {
disposeAllTunnels,
@@ -76,13 +77,14 @@ class FakeTunnelConn {
}
}
-const HOST_CFG = {
+const HOST_CFG: HostConfig = {
id: 'test-host',
hostname: '10.0.0.1',
port: 22,
user: 'deploy',
authMethod: 'agent' as const,
source: 'manual' as const,
+ managedByCindy: false,
};
const TUNNEL_PREF: SshHostAgentProxyPref = {
@@ -329,6 +331,34 @@ describe('agent-proxy tunnel keeper', () => {
});
});
+ it('rebuilds when effective SSH agent metadata changes', async () => {
+ const h = makeHarness();
+ h.mainHost.config = {
+ ...HOST_CFG,
+ sshAuthentication: {
+ identitiesOnly: false,
+ identityAgent: '/tmp/agent-a.sock',
+ configuredIdentityFiles: [],
+ identityFileDirectiveSeen: false,
+ identityFileNoneSeen: false,
+ },
+ };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ h.mainHost.config = {
+ ...h.mainHost.config,
+ sshAuthentication: {
+ ...h.mainHost.config.sshAuthentication!,
+ identityAgent: '/tmp/agent-b.sock',
+ },
+ };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ ensureTunnelForHost(h.mainHost as any, { allowRebuild: true });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await ensureTunnelUp(h.mainHost as any, 5_000);
+ expect(h.conns).toHaveLength(2);
+ });
+
it('late teardown of a replaced entry does not clobber the new active state (R3 review P2)', async () => {
const h = makeHarness();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts
index 5b9c6517b0..5758026145 100644
--- a/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts
+++ b/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts
@@ -17,6 +17,7 @@ import {
ensureRemoteCodexMcpBridge,
stripRemoteCodexMcpConfig,
hasPendingRemoteMcpDrift,
+ invalidateRemoteCodexMcpEndpointState,
} from '../codex-remote-mcp.js';
// safeStorage 在测试 stub 里 isEncryptionAvailable=false → token 真源恒 null;
@@ -655,6 +656,28 @@ describe('ensureRemoteCodexMcpBridge server whitelist', () => {
describe('ensureRemoteCodexMcpBridge drift self-heal (appliedFingerprint)', () => {
+ it('preserves the alias port but clears endpoint-specific MCP state', async () => {
+ const { host } = fakeHost('host-endpoint-change', '');
+ const result = await ensureRemoteCodexMcpBridge(host, {
+ ensureBridgeStarted: async () => ({
+ port: 38080,
+ serverNames: SERVERS,
+ bridgeInstanceId: 'bridge-endpoint-change',
+ }),
+ hasLiveTurnOnHost: () => false,
+ });
+ expect(result.ok).toBe(true);
+ expect(prefsOf('host-endpoint-change')).toMatchObject({
+ remotePort: 47921,
+ appliedFingerprint: expect.any(String),
+ bridgeLocalPort: 38080,
+ });
+
+ invalidateRemoteCodexMcpEndpointState('host-endpoint-change');
+
+ expect(prefsOf('host-endpoint-change')).toEqual({ remotePort: 47921 });
+ });
+
it('bootstraps on the next ensure once the live turn settles (deferred drift stays persistent)', async () => {
// defer 语义回归:live turn 期间 config 照写但 bootstrap 推迟;漂移未生效
// 是持久指纹事实 — turn 结束 (hasLiveTurn=false) 后的 ensure 即使
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/connectFailure.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/connectFailure.test.ts
index 442da08a69..f9a4ff3c7b 100644
--- a/apps/desktop/src/main/remote-ssh/__tests__/connectFailure.test.ts
+++ b/apps/desktop/src/main/remote-ssh/__tests__/connectFailure.test.ts
@@ -9,6 +9,8 @@ import {
KEY_FILE_NOT_FOUND_CODE,
KEY_FILE_UNREADABLE_CODE,
PINNED_AGENT_FAILED_CODE,
+ SSH_AGENT_UNAVAILABLE_CODE,
+ SSH_CONFIG_AUTH_UNSUPPORTED_CODE,
} from '@cindy/maker-remote-ssh';
import { classifyConnectFailure } from '../connect-failure.js';
@@ -55,4 +57,22 @@ describe('classifyConnectFailure', () => {
expect(classifyConnectFailure('connection closed before ready').code).toBe('SSH_CONNECT_FAILED');
expect(classifyConnectFailure(undefined).code).toBe('SSH_CONNECT_FAILED');
});
+
+ it('surfaces the explicit Cindy authentication subset error', () => {
+ const err = new Error('SSH config authentication is outside Cindy\'s supported subset: IdentityAgent none');
+ (err as { code?: string }).code = SSH_CONFIG_AUTH_UNSUPPORTED_CODE;
+ expect(classifyConnectFailure(err)).toMatchObject({
+ code: 'SSH_CONFIG_AUTH_UNSUPPORTED',
+ msg: err.message,
+ });
+ });
+
+ it('surfaces an unavailable local SSH Agent separately from unsupported config', () => {
+ const err = new Error('$SSH_AUTH_SOCK is not set');
+ (err as { code?: string }).code = SSH_AGENT_UNAVAILABLE_CODE;
+ expect(classifyConnectFailure(err)).toEqual({
+ code: 'SSH_AGENT_UNAVAILABLE',
+ msg: err.message,
+ });
+ });
});
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/hydrationQueue.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/hydrationQueue.test.ts
new file mode 100644
index 0000000000..460f0ba5b1
--- /dev/null
+++ b/apps/desktop/src/main/remote-ssh/__tests__/hydrationQueue.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+
+import { RemoteHostHydrationQueue } from '../hydration-queue.js';
+
+describe('RemoteHostHydrationQueue', () => {
+ it('serializes operations and continues after a rejection', async () => {
+ const queue = new RemoteHostHydrationQueue();
+ const events: string[] = [];
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+
+ const first = queue.run(async () => {
+ events.push('first:start');
+ await gate;
+ events.push('first:end');
+ throw new Error('expected');
+ });
+ const second = queue.run(async () => {
+ events.push('second');
+ return 2;
+ });
+
+ await Promise.resolve();
+ expect(events).toEqual(['first:start']);
+ release();
+ await expect(first).rejects.toThrow('expected');
+ await expect(second).resolves.toBe(2);
+ expect(events).toEqual(['first:start', 'first:end', 'second']);
+ });
+
+ it('keeps a queued reload from hydrating a snapshot taken before remove completes', async () => {
+ const queue = new RemoteHostHydrationQueue();
+ let diskHosts = ['remove-me'];
+ let poolHosts = ['remove-me'];
+ let releaseRemove!: () => void;
+ const removeWrite = new Promise<void>((resolve) => { releaseRemove = resolve; });
+
+ const remove = queue.run(async () => {
+ await removeWrite;
+ diskHosts = [];
+ poolHosts = [...diskHosts];
+ });
+ const reload = queue.run(async () => {
+ poolHosts = [...diskHosts];
+ });
+
+ await Promise.resolve();
+ expect(poolHosts).toEqual(['remove-me']);
+ releaseRemove();
+ await Promise.all([remove, reload]);
+ expect(poolHosts).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationContract.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationContract.test.ts
new file mode 100644
index 0000000000..5a583fd373
--- /dev/null
+++ b/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationContract.test.ts
@@ -0,0 +1,136 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const source = readFileSync(resolve(__dirname, '..', 'index.ts'), 'utf8').replace(/\r\n?/g, '\n');
+
+function handlerBody(channel: string, nextChannel: string): string {
+ const start = source.indexOf(`ipcMain.handle(REMOTE_SSH_INVOKE.${channel}`);
+ const end = source.indexOf(`ipcMain.handle(REMOTE_SSH_INVOKE.${nextChannel}`, start + 1);
+ expect(start).toBeGreaterThan(-1);
+ expect(end).toBeGreaterThan(start);
+ return source.slice(start, end);
+}
+
+describe('remote SSH managed-host mutation contract', () => {
+ it.each([
+ ['LIST', 'RELOAD_CONFIG'],
+ ['RELOAD_CONFIG', 'ADD'],
+ ])('%s validates the app renderer before reading SSH config', (channel, nextChannel) => {
+ const body = handlerBody(channel, nextChannel);
+ const guard = body.indexOf('assertTrustedAppRendererEvent(event);');
+ const read = Math.min(
+ ...[
+ body.indexOf('ensureHydrated()'),
+ body.indexOf('hydrateRemoteHosts()'),
+ ].filter((index) => index >= 0),
+ );
+ expect(guard).toBeGreaterThan(-1);
+ expect(guard).toBeLessThan(read);
+ });
+
+ it.each([
+ ['ADD', 'UPDATE'],
+ ['UPDATE', 'REMOVE'],
+ ['REMOVE', 'CONNECT'],
+ ])('%s validates the app renderer before parsing input', (channel, nextChannel) => {
+ const body = handlerBody(channel, nextChannel);
+ const guard = body.indexOf('assertTrustedAppRendererEvent(event);');
+ const parse = Math.min(
+ ...[
+ body.indexOf('normalizeAddInput('),
+ body.indexOf('requireObject('),
+ ].filter((index) => index >= 0),
+ );
+ expect(guard).toBeGreaterThan(-1);
+ expect(guard).toBeLessThan(parse);
+ });
+
+ it('serializes add, update, and remove with config reloads', () => {
+ for (const [channel, nextChannel] of [
+ ['ADD', 'UPDATE'],
+ ['UPDATE', 'REMOVE'],
+ ['REMOVE', 'CONNECT'],
+ ]) {
+ expect(handlerBody(channel, nextChannel))
+ .toContain('return remoteHostHydrationQueue.run(async () => {');
+ }
+ });
+
+ it('does not disconnect existing aliases when an add write or refresh fails', () => {
+ const body = handlerBody('ADD', 'UPDATE');
+ const hostWrite = body.indexOf('await addManagedHostWithInclude(');
+ const hydrate = body.indexOf('await hydrateRemoteHostsUnqueued(new Set(), true, new Set([cfg.id]));');
+ const reloadError = body.indexOf("throwReloadRequired('新主机'");
+
+ expect(hostWrite).toBeGreaterThan(-1);
+ expect(hydrate).toBeGreaterThan(hostWrite);
+ expect(reloadError).toBeGreaterThan(hydrate);
+ expect(body).not.toContain('invalidateHostRuntimeState(');
+ expect(body).not.toContain('.disconnect(');
+ expect(source).toContain('if (preserveExistingEndpoints && changedOrRemoved.length > 0)');
+ });
+
+ it('checks ownership before publishing a hydrated pool and rolls back add conflicts', () => {
+ const hydrateSource = source.slice(
+ source.indexOf('async function hydrateRemoteHostsUnqueued('),
+ source.indexOf('function hydrateRemoteHosts()', source.indexOf('async function hydrateRemoteHostsUnqueued(')),
+ );
+ const ownershipCheck = hydrateSource.indexOf('requiredManagedAliases');
+ const poolPublish = hydrateSource.indexOf('await getPool().hydrate(result.hosts);');
+ expect(ownershipCheck).toBeGreaterThan(-1);
+ expect(ownershipCheck).toBeLessThan(poolPublish);
+
+ const body = handlerBody('ADD', 'UPDATE');
+ const hydrate = body.indexOf('await hydrateRemoteHostsUnqueued(new Set(), true, new Set([cfg.id]));');
+ const rollback = body.indexOf('await addReceipt.rollback();');
+ const prefs = body.indexOf('patchSshHostPrefOrThrow(cfg.id');
+ expect(rollback).toBeGreaterThan(hydrate);
+ expect(rollback).toBeLessThan(prefs);
+ expect(body).toContain('instanceof SshHostOwnershipConflictError');
+ });
+
+ it('rejects external connection-field edits and writes before invalidating an owned endpoint', () => {
+ const body = handlerBody('UPDATE', 'REMOVE');
+ const diskRead = body.indexOf('const latest = await readLatestSshConfigOrThrow();');
+ const readOnlyGuard = body.indexOf('if (!latestHost?.managedByCindy)');
+ const write = body.indexOf('await updateManagedHostFields(');
+ const invalidate = body.indexOf('await invalidateHostRuntimeState(input.id);');
+ const hydrate = body.indexOf('await hydrateRemoteHostsUnqueued(new Set([input.id]));');
+
+ expect(diskRead).toBeGreaterThan(-1);
+ expect(readOnlyGuard).toBeGreaterThan(diskRead);
+ expect(readOnlyGuard).toBeLessThan(write);
+ expect(body).toContain('managedWriteTokenOrThrow(latest)');
+ expect(body).toContain('managedSshConfigPath, managedWriteToken!');
+ expect(write).toBeLessThan(invalidate);
+ expect(invalidate).toBeLessThan(hydrate);
+ });
+
+ it('writes a remove before disconnecting the target and never deletes external hosts', () => {
+ const body = handlerBody('REMOVE', 'CONNECT');
+ const diskRead = body.indexOf('const latest = await readLatestSshConfigOrThrow();');
+ const ownershipGuard = body.indexOf('if (!latestHost?.managedByCindy)');
+ const write = body.indexOf('await removeManagedHost(');
+ const invalidate = body.indexOf('await invalidateHostRuntimeState(id);');
+ const hydrate = body.indexOf('await hydrateRemoteHostsUnqueued(new Set([id]));');
+
+ expect(diskRead).toBeGreaterThan(-1);
+ expect(ownershipGuard).toBeGreaterThan(diskRead);
+ expect(ownershipGuard).toBeLessThan(write);
+ expect(body).toContain('const managedWriteToken = managedWriteTokenOrThrow(latest);');
+ expect(body).toContain('managedSshConfigPath, managedWriteToken');
+ expect(write).toBeLessThan(invalidate);
+ expect(invalidate).toBeLessThan(hydrate);
+ });
+
+ it('uses managed ownership instead of the legacy manual source marker', () => {
+ const mutationSource = source.slice(
+ source.indexOf('ipcMain.handle(REMOTE_SSH_INVOKE.ADD'),
+ source.indexOf('ipcMain.handle(REMOTE_SSH_INVOKE.CONNECT'),
+ );
+ expect(mutationSource).not.toContain("source === 'manual'");
+ expect(mutationSource).toContain('managedByCindy');
+ });
+});
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationRuntime.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationRuntime.test.ts
new file mode 100644
index 0000000000..1abdfb6e30
--- /dev/null
+++ b/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationRuntime.test.ts
@@ -0,0 +1,635 @@
+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type {
+ HostConfig,
+ ManagedConfigWriteToken,
+ ReadSshConfigResult,
+} from '@cindy/maker-remote-ssh';
+
+const mocks = vi.hoisted(() => ({
+ handlers: new Map<string, (...args: any[]) => Promise<unknown> | unknown>(),
+ readSshConfigDetailed: vi.fn(),
+ addManagedHostWithInclude: vi.fn(),
+ rollbackAdd: vi.fn(),
+ updateManagedHostFields: vi.fn(),
+ removeManagedHost: vi.fn(),
+ patchPref: vi.fn(),
+ removePref: vi.fn(),
+ clearAgentProxy: vi.fn(),
+ removeMcpPref: vi.fn(),
+ invalidateMcpEndpoint: vi.fn(),
+ dbLimit: vi.fn(),
+ logWarn: vi.fn(),
+}));
+
+vi.mock('../../logger.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../logger.js')>();
+ return {
+ ...actual,
+ createLogger: () => ({
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: mocks.logWarn,
+ error: vi.fn(),
+ }),
+ };
+});
+
+vi.mock('electron', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('electron')>();
+ return {
+ ...actual,
+ ipcMain: {
+ ...actual.ipcMain,
+ handle: vi.fn((channel: string, handler: (...args: any[]) => unknown) => {
+ mocks.handlers.set(channel, handler);
+ }),
+ },
+ BrowserWindow: class {
+ static getAllWindows(): never[] { return []; }
+ },
+ };
+});
+
+vi.mock('@cindy/maker-remote-ssh', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@cindy/maker-remote-ssh')>();
+ return {
+ ...actual,
+ defaultSshConfigPath: () => '/virtual/.ssh/config',
+ defaultManagedSshConfigPath: () => '/virtual/.ssh/cindy.conf',
+ readSshConfigDetailed: mocks.readSshConfigDetailed,
+ addManagedHostWithInclude: mocks.addManagedHostWithInclude,
+ updateManagedHostFields: mocks.updateManagedHostFields,
+ removeManagedHost: mocks.removeManagedHost,
+ };
+});
+
+vi.mock('../../security/trustedAppRenderer.js', () => ({
+ assertTrustedAppRendererEvent: vi.fn(),
+}));
+
+vi.mock('../../localDb/client/current.js', () => ({
+ getDbClient: () => ({
+ drizzle: {
+ select: () => ({
+ from: () => ({
+ where: () => ({ limit: mocks.dbLimit }),
+ }),
+ }),
+ },
+ }),
+}));
+
+vi.mock('../ssh-host-prefs-store.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../ssh-host-prefs-store.js')>();
+ return {
+ ...actual,
+ getSshHostAgentProxy: () => null,
+ getSshHostAutoConnect: () => false,
+ getSshHostDisplayName: (hostId: string) => hostId,
+ hasAnyAutoConnectHost: () => false,
+ readSshHostPrefs: () => ({}),
+ patchSshHostPref: mocks.patchPref,
+ removeSshHostPref: mocks.removePref,
+ setSshHostAutoConnect: vi.fn(),
+ };
+});
+
+vi.mock('../agent-proxy.js', () => ({
+ applyAgentProxyForHost: vi.fn(async () => undefined),
+ clearAgentProxyTunnelState: mocks.clearAgentProxy,
+ clearAgentProxyTunnelStateAndWait: vi.fn(async () => undefined),
+ disposeAllTunnels: vi.fn(async () => undefined),
+ getAgentProxyTunnelState: () => null,
+ getRemoteAgentProxyEnvUppercase: () => ({}),
+ handleAgentProxyMainHostDown: vi.fn(),
+ initAgentProxy: vi.fn(),
+ killRemoteCodexDaemon: vi.fn(async () => undefined),
+ reconcileCodexAgentProxyEnv: vi.fn(async () => undefined),
+ teardownAgentProxyOnUserDisconnect: vi.fn(async () => undefined),
+}));
+
+vi.mock('../cc-manager-install.js', () => ({
+ clearCcManagerInstallCache: vi.fn(),
+ runCcMgrUpgrade: vi.fn(),
+ listPendingCcMgrUpgrades: vi.fn(() => []),
+ dismissPendingCcMgrUpgrade: vi.fn(),
+ ensureCcManagerInstalledOrInstall: vi.fn(),
+}));
+
+vi.mock('../codex-remote-mcp.js', () => ({
+ invalidateRemoteCodexMcpEndpointState: mocks.invalidateMcpEndpoint,
+ removeRemoteMcpForwardPref: mocks.removeMcpPref,
+}));
+
+vi.mock('../../maker-host/index.js', () => ({
+ getMakerIfReady: () => null,
+ softCloseCcSessionsForHost: vi.fn(async () => undefined),
+}));
+
+import {
+ getRemoteSshPool,
+ registerRemoteSshIpc,
+ REMOTE_SSH_INVOKE,
+} from '../index.js';
+
+function host(id: string, overrides: Partial<HostConfig> = {}): HostConfig {
+ return {
+ id,
+ hostname: `192.0.2.${id.length}`,
+ port: 22,
+ user: 'developer',
+ authMethod: 'agent',
+ source: 'ssh-config',
+ managedByCindy: true,
+ ...overrides,
+ };
+}
+
+function successfulRead(hosts: HostConfig[]): ReadSshConfigResult {
+ return {
+ hosts,
+ diagnostic: null,
+ warnings: [],
+ managedConfigWriteToken: 'a'.repeat(64) as ManagedConfigWriteToken,
+ };
+}
+
+function failedRead(): ReadSshConfigResult {
+ return {
+ hosts: [],
+ diagnostic: {
+ path: '/virtual/.ssh/config',
+ kind: 'syntax',
+ message: 'fixture parse failure',
+ recoveryHint: 'fix fixture',
+ },
+ warnings: [],
+ };
+}
+
+function handler(channel: string): (...args: any[]) => Promise<any> {
+ const registered = mocks.handlers.get(channel);
+ if (!registered) throw new Error(`handler not registered: ${channel}`);
+ return async (...args: any[]) => registered(...args);
+}
+
+let initialListResult: {
+ hosts: unknown[];
+ warningCount: number;
+ diagnostic: { kind: string } | null;
+};
+
+beforeAll(async () => {
+ mocks.readSshConfigDetailed.mockResolvedValue(failedRead());
+ registerRemoteSshIpc();
+ initialListResult = await handler(REMOTE_SSH_INVOKE.LIST)({});
+ mocks.readSshConfigDetailed.mockResolvedValue(successfulRead([]));
+ await handler(REMOTE_SSH_INVOKE.RELOAD_CONFIG)({});
+});
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ mocks.readSshConfigDetailed.mockReset();
+ mocks.rollbackAdd.mockReset().mockResolvedValue(true);
+ mocks.addManagedHostWithInclude.mockResolvedValue({ rollback: mocks.rollbackAdd });
+ mocks.updateManagedHostFields.mockResolvedValue(undefined);
+ mocks.removeManagedHost.mockResolvedValue(undefined);
+ mocks.invalidateMcpEndpoint.mockReset();
+ mocks.dbLimit.mockReset().mockResolvedValue([]);
+ mocks.logWarn.mockReset();
+ await getRemoteSshPool().hydrate([]);
+ mocks.readSshConfigDetailed.mockImplementation(async () => successfulRead(
+ getRemoteSshPool().list().map((snapshot) => snapshot.config),
+ ));
+});
+
+describe('remote SSH mutation runtime semantics', () => {
+ it('returns a cold-start diagnostic instead of making the host list look valid and empty', () => {
+ expect(initialListResult).toMatchObject({
+ hosts: [],
+ warningCount: 0,
+ diagnostic: { kind: 'syntax' },
+ });
+ });
+
+ it('does not expose main-only SSH authentication metadata or warning paths over LIST IPC', async () => {
+ const visible = host('visible', {
+ identityFile: '/Users/example/.ssh/private.key',
+ sshAuthentication: {
+ identitiesOnly: true,
+ identityAgent: '/private/tmp/agent.sock',
+ configuredIdentityFiles: ['/Users/example/.ssh/private.key'],
+ identityFileDirectiveSeen: true,
+ identityFileNoneSeen: false,
+ allowedAgentFingerprints: ['SHA256:secret-fingerprint'],
+ },
+ });
+ mocks.readSshConfigDetailed.mockResolvedValueOnce({
+ hosts: [visible],
+ diagnostic: null,
+ warnings: ['/Users/example/.ssh/config:12: unsupported conditional Include'],
+ });
+
+ const result = await handler(REMOTE_SSH_INVOKE.RELOAD_CONFIG)({});
+ expect(result.warningCount).toBe(1);
+ expect(result).not.toHaveProperty('warnings');
+ expect(result).not.toHaveProperty('managedConfigWriteToken');
+ expect(result.hosts[0].config).not.toHaveProperty('sshAuthentication');
+ expect(result.hosts[0].config).not.toHaveProperty('identityFile');
+ expect(result.hosts[0].config).toMatchObject({
+ identityFileConfigured: true,
+ identityFileName: 'private.key',
+ });
+ expect(JSON.stringify(result)).not.toContain('secret-fingerprint');
+ expect(JSON.stringify(result)).not.toContain('/Users/example/.ssh/private.key');
+ expect(JSON.stringify(result)).not.toContain('/Users/example/.ssh/config');
+ });
+
+ it('preserves an existing main-only identity path when Renderer edits other fields', async () => {
+ const current = host('preserve-key', {
+ authMethod: 'key',
+ identityFile: '/Users/example/.ssh/preserve.key',
+ });
+ await getRemoteSshPool().hydrate([current]);
+ const onDisk = { ...getRemoteSshPool().get(current.id)!.config };
+ const updated = { ...onDisk, hostname: '192.0.2.210' };
+ mocks.readSshConfigDetailed
+ .mockResolvedValueOnce(successfulRead([onDisk]))
+ .mockResolvedValueOnce(successfulRead([onDisk]))
+ .mockResolvedValueOnce(successfulRead([updated]));
+
+ const result = await handler(REMOTE_SSH_INVOKE.UPDATE)({}, {
+ id: current.id,
+ displayName: current.id,
+ hostname: updated.hostname,
+ port: current.port,
+ user: current.user,
+ authMethod: current.authMethod,
+ identityFileUnchanged: true,
+ });
+
+ expect(mocks.updateManagedHostFields).toHaveBeenCalledWith(
+ expect.objectContaining({ identityFile: current.identityFile }),
+ expect.any(String),
+ 'a'.repeat(64),
+ );
+ expect(result.host.config).toMatchObject({
+ identityFileConfigured: true,
+ identityFileName: 'preserve.key',
+ });
+ expect(JSON.stringify(result)).not.toContain('/Users/example/.ssh/preserve.key');
+ });
+
+ it('keeps a live endpoint connected when UPDATE cannot write', async () => {
+ const current = host('managed');
+ await getRemoteSshPool().hydrate([current]);
+ const live = getRemoteSshPool().get(current.id)!;
+ const disconnect = vi.spyOn(live, 'disconnect').mockResolvedValue();
+ mocks.updateManagedHostFields.mockRejectedValueOnce(
+ new Error('EACCES: cannot write /Users/example/.ssh/cindy.conf'),
+ );
+
+ const error = await handler(REMOTE_SSH_INVOKE.UPDATE)({}, {
+ ...current,
+ hostname: '192.0.2.99',
+ displayName: current.id,
+ }).catch((caught) => caught);
+
+ expect(error).toMatchObject({ code: 'SSH_CONFIG_IO_FAILED' });
+ expect(error.message).not.toContain('/Users/example/.ssh/cindy.conf');
+
+ expect(disconnect).not.toHaveBeenCalled();
+ expect(live.config.hostname).toBe(current.hostname);
+ });
+
+ it.each([
+ ['UPDATE', mocks.updateManagedHostFields],
+ ['REMOVE', mocks.removeManagedHost],
+ ] as const)('maps a concurrent managed-file change during %s without mutating runtime state', async (operation, writer) => {
+ const current = host(`concurrent-${operation.toLowerCase()}`);
+ await getRemoteSshPool().hydrate([current]);
+ const live = getRemoteSshPool().get(current.id)!;
+ const disconnect = vi.spyOn(live, 'disconnect').mockResolvedValue();
+ const conflict = new Error('config changed') as Error & { code?: string };
+ conflict.code = 'SSH_CONFIG_CONCURRENT_MODIFICATION';
+ writer.mockRejectedValueOnce(conflict);
+
+ const request = operation === 'UPDATE'
+ ? handler(REMOTE_SSH_INVOKE.UPDATE)({}, {
+ ...current,
+ hostname: '192.0.2.199',
+ displayName: current.id,
+ })
+ : handler(REMOTE_SSH_INVOKE.REMOVE)({}, { id: current.id });
+ await expect(request).rejects.toMatchObject({
+ code: 'SSH_CONFIG_CONCURRENT_MODIFICATION',
+ });
+ expect(disconnect).not.toHaveBeenCalled();
+ expect(mocks.patchPref).not.toHaveBeenCalled();
+ expect(mocks.removePref).not.toHaveBeenCalled();
+ expect(getRemoteSshPool().get(current.id)).toBe(live);
+ });
+
+ it('rejects a missing managed write token as an internal contract error', async () => {
+ const current = host('missing-write-token');
+ await getRemoteSshPool().hydrate([current]);
+ mocks.readSshConfigDetailed.mockResolvedValueOnce({
+ hosts: [current],
+ diagnostic: null,
+ warnings: [],
+ });
+
+ await expect(handler(REMOTE_SSH_INVOKE.UPDATE)({}, {
+ ...current,
+ hostname: '192.0.2.188',
+ displayName: current.id,
+ })).rejects.toMatchObject({ code: 'INTERNAL' });
+ expect(mocks.updateManagedHostFields).not.toHaveBeenCalled();
+ expect(JSON.stringify(mocks.logWarn.mock.calls)).not.toContain('a'.repeat(64));
+ });
+
+ it('keeps database details out of IPC and the remote-ssh log scope', async () => {
+ const current = host('db-failure');
+ await getRemoteSshPool().hydrate([current]);
+ const sensitive = 'SQL SELECT secret FROM sessions at /Users/alice/cindy.db value=private';
+ mocks.dbLimit.mockRejectedValueOnce(Object.assign(new Error(sensitive), {
+ code: 'SQLITE_BUSY',
+ }));
+
+ const error = await handler(REMOTE_SSH_INVOKE.REMOVE)({}, { id: current.id })
+ .catch((caught) => caught);
+ expect(error).toMatchObject({ code: 'INTERNAL' });
+ expect(error.message).not.toContain(sensitive);
+ expect(JSON.stringify(mocks.logWarn.mock.calls)).not.toContain(sensitive);
+ expect(JSON.stringify(mocks.logWarn.mock.calls)).toContain('SQLITE_BUSY');
+ expect(mocks.removeManagedHost).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['a thrown filesystem error', () => {
+ mocks.readSshConfigDetailed.mockRejectedValueOnce(
+ new Error('EACCES: cannot read /Users/example/.ssh/config'),
+ );
+ }],
+ ['a returned diagnostic', () => {
+ mocks.readSshConfigDetailed.mockResolvedValueOnce({
+ hosts: [],
+ diagnostic: {
+ path: '/Users/example/.ssh/included.conf',
+ kind: 'io',
+ message: 'EACCES: cannot read /Users/example/.ssh/included.conf',
+ recoveryHint: 'fix permissions',
+ },
+ warnings: [],
+ });
+ }],
+ ])('does not expose local paths when config preflight returns %s', async (_label, failRead) => {
+ const current = host('private-path');
+ await getRemoteSshPool().hydrate([current]);
+ failRead();
+
+ const error = await handler(REMOTE_SSH_INVOKE.UPDATE)({}, {
+ ...current,
+ hostname: '192.0.2.199',
+ displayName: current.id,
+ }).catch((caught) => caught);
+
+ expect(error).toMatchObject({ code: 'SSH_CONFIG_IO_FAILED' });
+ expect(error.message).not.toContain('/Users/example');
+ expect(error.message).not.toContain('EACCES');
+ });
+
+ it('keeps existing aliases connected when ADD writes but refresh fails', async () => {
+ const existing = host('existing');
+ await getRemoteSshPool().hydrate([existing]);
+ const live = getRemoteSshPool().get(existing.id)!;
+ const disconnect = vi.spyOn(live, 'disconnect').mockResolvedValue();
+ mocks.readSshConfigDetailed
+ .mockResolvedValueOnce(successfulRead([existing]))
+ .mockResolvedValueOnce(failedRead());
+
+ await expect(handler(REMOTE_SSH_INVOKE.ADD)({}, {
+ id: 'new-host',
+ hostname: '192.0.2.77',
+ user: 'developer',
+ })).rejects.toMatchObject({ code: 'SSH_CONFIG_RELOAD_REQUIRED' });
+
+ expect(disconnect).not.toHaveBeenCalled();
+ expect(getRemoteSshPool().get(existing.id)).toBe(live);
+ expect(getRemoteSshPool().get('new-host')).toBeUndefined();
+ expect(mocks.patchPref).toHaveBeenCalledWith('new-host', {
+ displayName: 'new-host',
+ });
+ });
+
+ it('rejects an ADD when the newly introduced alias is no longer Cindy-owned', async () => {
+ const conflicting = host('new-host', { managedByCindy: false });
+ mocks.readSshConfigDetailed
+ .mockResolvedValueOnce(successfulRead([]))
+ .mockResolvedValueOnce(successfulRead([conflicting]));
+
+ await expect(handler(REMOTE_SSH_INVOKE.ADD)({}, {
+ id: conflicting.id,
+ hostname: conflicting.hostname,
+ user: conflicting.user,
+ })).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+
+ expect(mocks.rollbackAdd).toHaveBeenCalledOnce();
+ expect(mocks.patchPref).not.toHaveBeenCalled();
+ expect(getRemoteSshPool().get(conflicting.id)).toBeUndefined();
+ });
+
+ it('does not report ADD success when the managed-file rollback cannot be confirmed', async () => {
+ const conflicting = host('rollback-unknown', { managedByCindy: false });
+ mocks.rollbackAdd.mockResolvedValueOnce(false);
+ mocks.readSshConfigDetailed
+ .mockResolvedValueOnce(successfulRead([]))
+ .mockResolvedValueOnce(successfulRead([conflicting]));
+
+ await expect(handler(REMOTE_SSH_INVOKE.ADD)({}, {
+ id: conflicting.id,
+ hostname: conflicting.hostname,
+ user: conflicting.user,
+ })).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+
+ expect(mocks.rollbackAdd).toHaveBeenCalledOnce();
+ expect(mocks.patchPref).not.toHaveBeenCalled();
+ expect(getRemoteSshPool().get(conflicting.id)).toBeUndefined();
+ });
+
+ it('reports a stable partial-success code when ADD commits but local prefs cannot be written', async () => {
+ const added = host('prefs-failed');
+ mocks.readSshConfigDetailed
+ .mockResolvedValueOnce(successfulRead([]))
+ .mockResolvedValueOnce(successfulRead([added]));
+ mocks.patchPref.mockImplementationOnce(() => {
+ throw new Error('userData is read-only');
+ });
+
+ await expect(handler(REMOTE_SSH_INVOKE.ADD)({}, {
+ id: added.id,
+ hostname: added.hostname,
+ user: added.user,
+ displayName: 'Friendly name',
+ })).rejects.toMatchObject({ code: 'SSH_HOST_PREFS_WRITE_FAILED' });
+
+ expect(mocks.addManagedHostWithInclude).toHaveBeenCalledOnce();
+ expect(getRemoteSshPool().get(added.id)?.config.id).toBe(added.id);
+ });
+
+ it('reports an ownership error when the existing managed SSH file is unclaimed', async () => {
+ const ownershipError = new Error('existing managed SSH config is not owned by Cindy') as Error & { code?: string };
+ ownershipError.code = 'SSH_CONFIG_OWNERSHIP_REQUIRED';
+ mocks.addManagedHostWithInclude.mockRejectedValueOnce(ownershipError);
+
+ await expect(handler(REMOTE_SSH_INVOKE.ADD)({}, {
+ id: 'unclaimed-file',
+ hostname: '192.0.2.73',
+ user: 'developer',
+ })).rejects.toMatchObject({ code: 'SSH_CONFIG_OWNERSHIP_REQUIRED' });
+ expect(mocks.patchPref).not.toHaveBeenCalled();
+ });
+
+ it('reports a stable local-prefs error instead of a raw filesystem failure on UPDATE', async () => {
+ const external = host('prefs-only', { managedByCindy: false });
+ await getRemoteSshPool().hydrate([external]);
+ mocks.patchPref.mockImplementationOnce(() => {
+ throw new Error('rename failed');
+ });
+
+ await expect(handler(REMOTE_SSH_INVOKE.UPDATE)({}, {
+ ...external,
+ displayName: 'Unsaved name',
+ })).rejects.toMatchObject({ code: 'SSH_HOST_PREFS_WRITE_FAILED' });
+
+ expect(mocks.updateManagedHostFields).not.toHaveBeenCalled();
+ expect(getRemoteSshPool().get(external.id)).toBeTruthy();
+ });
+
+ it('disconnects only the target when UPDATE writes but refresh fails', async () => {
+ const target = host('target');
+ const other = host('other');
+ await getRemoteSshPool().hydrate([target, other]);
+ const targetLive = getRemoteSshPool().get(target.id)!;
+ const otherLive = getRemoteSshPool().get(other.id)!;
+ const targetDisconnect = vi.spyOn(targetLive, 'disconnect').mockResolvedValue();
+ const otherDisconnect = vi.spyOn(otherLive, 'disconnect').mockResolvedValue();
+ mocks.readSshConfigDetailed
+ .mockResolvedValueOnce(successfulRead([target, other]))
+ .mockResolvedValueOnce(failedRead());
+
+ await expect(handler(REMOTE_SSH_INVOKE.UPDATE)({}, {
+ ...target,
+ hostname: '192.0.2.88',
+ displayName: target.id,
+ })).rejects.toMatchObject({ code: 'SSH_CONFIG_RELOAD_REQUIRED' });
+
+ expect(targetDisconnect).toHaveBeenCalledTimes(1);
+ expect(otherDisconnect).not.toHaveBeenCalled();
+ expect(targetLive.config.hostname).toBe(target.hostname);
+ expect(mocks.patchPref).toHaveBeenCalledWith(target.id, {
+ displayName: target.id,
+ });
+ });
+
+ it('disconnects only the target when REMOVE writes but refresh fails', async () => {
+ const target = host('remove-me');
+ const other = host('keep-me');
+ await getRemoteSshPool().hydrate([target, other]);
+ const targetLive = getRemoteSshPool().get(target.id)!;
+ const otherLive = getRemoteSshPool().get(other.id)!;
+ const targetDisconnect = vi.spyOn(targetLive, 'disconnect').mockResolvedValue();
+ const otherDisconnect = vi.spyOn(otherLive, 'disconnect').mockResolvedValue();
+ mocks.readSshConfigDetailed
+ .mockResolvedValueOnce(successfulRead([target, other]))
+ .mockResolvedValueOnce(failedRead());
+
+ await expect(handler(REMOTE_SSH_INVOKE.REMOVE)({}, { id: target.id }))
+ .rejects.toMatchObject({ code: 'SSH_CONFIG_RELOAD_REQUIRED' });
+
+ expect(targetDisconnect).toHaveBeenCalledTimes(1);
+ expect(otherDisconnect).not.toHaveBeenCalled();
+ expect(getRemoteSshPool().get(target.id)).toBe(targetLive);
+ expect(mocks.removePref).toHaveBeenCalledWith(target.id);
+ expect(mocks.clearAgentProxy).toHaveBeenCalledWith(target.id);
+ expect(mocks.removeMcpPref).toHaveBeenCalledWith(target.id);
+ });
+
+ it('still disconnects the target when endpoint cleanup fails after UPDATE writes', async () => {
+ const target = host('cleanup-failure');
+ await getRemoteSshPool().hydrate([target]);
+ const targetLive = getRemoteSshPool().get(target.id)!;
+ const disconnect = vi.spyOn(targetLive, 'disconnect').mockResolvedValue();
+ mocks.invalidateMcpEndpoint.mockImplementationOnce(() => {
+ throw new Error('prefs disk unavailable');
+ });
+
+ await expect(handler(REMOTE_SSH_INVOKE.UPDATE)({}, {
+ ...target,
+ hostname: '192.0.2.89',
+ displayName: target.id,
+ })).rejects.toMatchObject({ code: 'SSH_CONFIG_RELOAD_REQUIRED' });
+
+ expect(mocks.updateManagedHostFields).toHaveBeenCalledOnce();
+ expect(disconnect).toHaveBeenCalledOnce();
+ expect(getRemoteSshPool().get(target.id)).toBe(targetLive);
+ expect(targetLive.config.hostname).toBe(target.hostname);
+ });
+
+ it('rejects external connection edits but allows local preference edits', async () => {
+ const external = host('external', { managedByCindy: false });
+ await getRemoteSshPool().hydrate([external]);
+
+ await expect(handler(REMOTE_SSH_INVOKE.UPDATE)({}, {
+ ...external,
+ hostname: '192.0.2.111',
+ displayName: 'Renamed',
+ })).rejects.toMatchObject({ code: 'SSH_CONFIG_OWNERSHIP_REQUIRED' });
+ expect(mocks.updateManagedHostFields).not.toHaveBeenCalled();
+
+ await expect(handler(REMOTE_SSH_INVOKE.UPDATE)({}, {
+ ...external,
+ displayName: 'Renamed',
+ agentProxy: null,
+ })).resolves.toMatchObject({
+ host: { config: { id: external.id } },
+ });
+ expect(mocks.patchPref).toHaveBeenCalledWith(external.id, {
+ displayName: 'Renamed',
+ agentProxy: null,
+ });
+ expect(mocks.updateManagedHostFields).not.toHaveBeenCalled();
+ });
+
+ it('refuses UPDATE when the latest disk graph no longer uniquely owns the alias', async () => {
+ const managed = host('duplicate-update');
+ await getRemoteSshPool().hydrate([managed]);
+ mocks.readSshConfigDetailed.mockResolvedValueOnce(successfulRead([
+ { ...managed, managedByCindy: false },
+ ]));
+
+ await expect(handler(REMOTE_SSH_INVOKE.UPDATE)({}, {
+ ...managed,
+ hostname: '192.0.2.200',
+ displayName: managed.id,
+ })).rejects.toMatchObject({ code: 'SSH_CONFIG_OWNERSHIP_REQUIRED' });
+
+ expect(mocks.updateManagedHostFields).not.toHaveBeenCalled();
+ });
+
+ it('refuses REMOVE when the latest disk graph no longer uniquely owns the alias', async () => {
+ const managed = host('duplicate-remove');
+ await getRemoteSshPool().hydrate([managed]);
+ mocks.readSshConfigDetailed.mockResolvedValueOnce(successfulRead([
+ { ...managed, managedByCindy: false },
+ ]));
+
+ await expect(handler(REMOTE_SSH_INVOKE.REMOVE)({}, { id: managed.id }))
+ .rejects.toMatchObject({ code: 'SSH_CONFIG_OWNERSHIP_REQUIRED' });
+
+ expect(mocks.removeManagedHost).not.toHaveBeenCalled();
+ expect(mocks.removePref).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/remote-ssh/agent-proxy-tunnel.ts b/apps/desktop/src/main/remote-ssh/agent-proxy-tunnel.ts
index 1cc3bedcbc..19eeb24331 100644
--- a/apps/desktop/src/main/remote-ssh/agent-proxy-tunnel.ts
+++ b/apps/desktop/src/main/remote-ssh/agent-proxy-tunnel.ts
@@ -32,7 +32,11 @@
* **不** rebuild (allowRebuild=false 时 pref 变化只沿用旧隧道)。
*/
-import type { HostConfig, RemoteHost } from '@cindy/maker-remote-ssh';
+import {
+ effectiveAuthenticationFingerprint,
+ type HostConfig,
+ type RemoteHost,
+} from '@cindy/maker-remote-ssh';
import type { AgentProxyTunnelState } from '../../shared/agentProxyConfig.js';
import type { SshHostAgentProxyPref } from './ssh-host-prefs-store.js';
@@ -125,8 +129,7 @@ function entryKey(
cfg.hostname,
cfg.port,
cfg.user,
- cfg.authMethod,
- cfg.identityFile ?? '',
+ effectiveAuthenticationFingerprint(cfg),
pref.localHost,
pref.localPort,
pref.remotePort,
diff --git a/apps/desktop/src/main/remote-ssh/agent-proxy.ts b/apps/desktop/src/main/remote-ssh/agent-proxy.ts
index ef00d4db5c..d0096c02c2 100644
--- a/apps/desktop/src/main/remote-ssh/agent-proxy.ts
+++ b/apps/desktop/src/main/remote-ssh/agent-proxy.ts
@@ -69,6 +69,12 @@ export function clearAgentProxyTunnelState(hostId: string): void {
void stopTunnelForHost(hostId);
}
+/** Awaited endpoint-edit variant so a late tunnel stop cannot race rehydrate. */
+export async function clearAgentProxyTunnelStateAndWait(hostId: string): Promise<void> {
+ tunnelStates.delete(hostId);
+ await stopTunnelForHost(hostId);
+}
+
/**
* 主控制连接断开时的处理: 隧道保活挂起 (不空转重试), 但**存活的隧道不拆**
* — 独立连接可能还在正常服务 LLM 流量, 主连接的断链不该牵连它。主连接
diff --git a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
index 4c0807a9b1..7abf8fc91c 100644
--- a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
+++ b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
@@ -184,6 +184,21 @@ export function removeRemoteMcpForwardPref(hostId: string): void {
writePortPrefs(next);
}
+/**
+ * Endpoint fields changed while the stable SSH alias stayed the same.
+ * Keep the alias's preferred remote port, but discard facts that only apply to
+ * the old machine/connection. The next ensure must rebuild the forward and
+ * bootstrap the new endpoint instead of trusting the old applied fingerprint.
+ */
+export function invalidateRemoteCodexMcpEndpointState(hostId: string): void {
+ const current = readPortPrefs()[hostId];
+ if (!current || (!current.appliedFingerprint && !current.bridgeLocalPort)) return;
+ writePortPrefs({
+ ...readPortPrefs(),
+ [hostId]: { remotePort: current.remotePort },
+ });
+}
+
// ── 远端 config.toml 管理段 (纯函数, 便于单测) ──────────────────────────────
/** 生成我们管理的 mcp_servers 配置块 (带 begin/end 标记)。 */
diff --git a/apps/desktop/src/main/remote-ssh/connect-failure.ts b/apps/desktop/src/main/remote-ssh/connect-failure.ts
index 16be9084ec..1fd441d540 100644
--- a/apps/desktop/src/main/remote-ssh/connect-failure.ts
+++ b/apps/desktop/src/main/remote-ssh/connect-failure.ts
@@ -8,11 +8,15 @@ import {
KEY_FILE_NOT_FOUND_CODE,
KEY_FILE_UNREADABLE_CODE,
PINNED_AGENT_FAILED_CODE,
+ SSH_AGENT_UNAVAILABLE_CODE,
+ SSH_CONFIG_AUTH_UNSUPPORTED_CODE,
} from '@cindy/maker-remote-ssh';
export type ConnectFailureClass =
| 'SSH_AUTH_FAILED'
| 'SSH_KEY_FILE_NOT_FOUND'
+ | 'SSH_AGENT_UNAVAILABLE'
+ | 'SSH_CONFIG_AUTH_UNSUPPORTED'
| 'SSH_CONNECT_FAILED';
/**
@@ -36,6 +40,12 @@ 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_CONFIG_AUTH_UNSUPPORTED_CODE) {
+ return { code: 'SSH_CONFIG_AUTH_UNSUPPORTED', msg };
+ }
+ if (code === SSH_AGENT_UNAVAILABLE_CODE) {
+ return { code: 'SSH_AGENT_UNAVAILABLE', msg };
+ }
if (
code === KEY_FILE_NOT_FOUND_CODE
|| code === KEY_FILE_UNREADABLE_CODE
diff --git a/apps/desktop/src/main/remote-ssh/hydration-queue.ts b/apps/desktop/src/main/remote-ssh/hydration-queue.ts
new file mode 100644
index 0000000000..8e391f6031
--- /dev/null
+++ b/apps/desktop/src/main/remote-ssh/hydration-queue.ts
@@ -0,0 +1,10 @@
+/** Serializes SSH config reads, writes, runtime invalidation, and hydration. */
+export class RemoteHostHydrationQueue {
+ private tail: Promise<void> = Promise.resolve();
+
+ run<T>(operation: () => Promise<T>): Promise<T> {
+ const task = this.tail.then(operation);
+ this.tail = task.then(() => undefined, () => undefined);
+ return task;
+ }
+}
diff --git a/apps/desktop/src/main/remote-ssh/index.ts b/apps/desktop/src/main/remote-ssh/index.ts
index 60af2daf75..80d21b6cdd 100644
--- a/apps/desktop/src/main/remote-ssh/index.ts
+++ b/apps/desktop/src/main/remote-ssh/index.ts
@@ -5,15 +5,16 @@
*
* maker:remote-ssh:list list hosts + status snapshots
* maker:remote-ssh:reload-config re-read ~/.ssh/config, refresh registry
- * maker:remote-ssh:add add a host (also writes ~/.ssh/config)
- * maker:remote-ssh:remove remove a host (also strips ~/.ssh/config)
+ * maker:remote-ssh:add add a Cindy-managed host
+ * maker:remote-ssh:remove remove a Cindy-managed host
* maker:remote-ssh:connect open the SSH connection
* maker:remote-ssh:disconnect close the SSH connection
* maker:remote-ssh:status-changed (push) host status fan-out
*
- * All host writes round-trip through ~/.ssh/config so the user can still
- * run `ssh <alias>` from the terminal. The pool itself is in-memory; on
- * app restart, hydrate() rebuilds it from disk.
+ * Cindy-managed hosts live in ~/.ssh/cindy.conf. The main ~/.ssh/config is
+ * only text-spliced to keep one early Include, so terminal `ssh <alias>` and
+ * Cindy discover the same aliases without rewriting hand-authored blocks.
+ * The pool itself is in-memory; on app restart, hydrate() rebuilds it from disk.
*/
import { app, ipcMain, BrowserWindow } from 'electron';
@@ -24,10 +25,12 @@ import os from 'node:os';
import {
ConnectionPool,
- readSshConfig,
- upsertHost,
- updateHostFields,
- removeHost as removeHostFromConfig,
+ addManagedHostWithInclude,
+ defaultManagedSshConfigPath,
+ defaultSshConfigPath,
+ readSshConfigDetailed,
+ removeManagedHost,
+ updateManagedHostFields,
installRemoteAgent,
PINNED_PI_VERSION,
probeRemoteAgent,
@@ -35,14 +38,23 @@ import {
checkRemoteCodexAuth,
pushRemoteCodexAuth,
expandHome,
+ effectiveAuthenticationFingerprint,
+ redactSshSensitiveText,
+ MANAGED_CONFIG_CONCURRENT_MODIFICATION_CODE,
+ MANAGED_CONFIG_OWNERSHIP_REQUIRED_CODE,
+ MANAGED_CONFIG_WRITE_TOKEN_REQUIRED_CODE,
FileHostKeyStore,
RemoteHost,
type AddHostInput,
type CodexAuthState,
type HostConfig,
type HostSnapshot,
+ type SshConfigDiagnostic,
type InstallProgressEvent,
type InstallResult,
+ type ManagedHostAddReceipt,
+ type ManagedConfigWriteToken,
+ type ReadSshConfigResult,
type RemoteAgentKind,
} from '@cindy/maker-remote-ssh';
@@ -74,19 +86,21 @@ import {
import {
getSshHostAgentProxy,
getSshHostAutoConnect,
+ getSshHostDisplayName,
hasAnyAutoConnectHost,
isAllowedAgentProxyRemotePort,
LEGACY_AGENT_PROXY_REMOTE_PORT,
normalizeAgentProxyUrl,
readSshHostPrefs,
+ patchSshHostPref,
removeSshHostPref,
- setSshHostAgentProxy,
setSshHostAutoConnect,
type SshHostAgentProxyPref,
} from './ssh-host-prefs-store.js';
import {
applyAgentProxyForHost,
clearAgentProxyTunnelState,
+ clearAgentProxyTunnelStateAndWait,
disposeAllTunnels,
getAgentProxyTunnelState,
getRemoteAgentProxyEnvUppercase,
@@ -104,10 +118,16 @@ import {
dismissPendingCcMgrUpgrade,
ensureCcManagerInstalledOrInstall,
} from './cc-manager-install.js';
-import { removeRemoteMcpForwardPref } from './codex-remote-mcp.js';
+import {
+ invalidateRemoteCodexMcpEndpointState,
+ removeRemoteMcpForwardPref,
+} from './codex-remote-mcp.js';
import { ensureDaemonRunning } from '../maker-host/cc-manager-client.js';
import { getMakerIfReady, softCloseCcSessionsForHost } from '../maker-host/index.js';
import { withRehydrateCloseSuppressed } from '../maker-host/rehydrateCloseSuppression.js';
+import { RemoteHostHydrationQueue } from './hydration-queue.js';
+
+export { redactSshSensitiveText };
const log = createLogger('remote-ssh/ipc');
/**
@@ -226,6 +246,24 @@ const VALID_AGENT_KINDS: ReadonlyArray<RemoteAgentKind> = ['claude-code', 'codex
let pool: ConnectionPool | null = null;
let initPromise: Promise<void> | null = null;
let registered = false;
+const sshConfigPath = defaultSshConfigPath();
+const managedSshConfigPath = defaultManagedSshConfigPath();
+const remoteHostHydrationQueue = new RemoteHostHydrationQueue();
+let sshConfigWarnings: string[] = [];
+let sshConfigDiagnostic: SshConfigDiagnostic | null = null;
+let remoteFileBrowserEndpointInvalidator: ((hostId: string) => Promise<void>) | null = null;
+const SSH_CONFIG_READ_FAILED_MESSAGE =
+ 'Unable to read SSH configuration. Check file permissions and Include paths, then refresh.';
+const SSH_CONFIG_WRITE_FAILED_MESSAGE =
+ 'Unable to write SSH configuration. Check file permissions, then try again.';
+
+class SshHostOwnershipConflictError extends Error {
+ constructor(readonly aliases: readonly string[]) {
+ super(`SSH host ownership changed while adding: ${aliases.join(', ')}`);
+ this.name = 'SshHostOwnershipConflictError';
+ }
+}
+
/** 与 pool 共享的 host-key store — agent-proxy 隧道专用连接也用它做 TOFU 校验。 */
let sharedHostKeyStore: FileHostKeyStore | null = null;
@@ -266,6 +304,13 @@ export function getRemoteSshPool(): ConnectionPool {
return getPool();
}
+/** Registered by file-browser without creating a reverse import cycle. */
+export function setRemoteFileBrowserEndpointInvalidator(
+ invalidator: ((hostId: string) => Promise<void>) | null,
+): void {
+ remoteFileBrowserEndpointInvalidator = invalidator;
+}
+
/** Pi's Responses client expects the provider base URL to end at the `/v1` API root. */
export function buildRemotePiQuickTestModelsJson(endpoint: string): string {
const trimmed = endpoint.trim().replace(/\/+$/, '');
@@ -315,7 +360,7 @@ export async function ensureRemoteHostReady(id: string): Promise<void> {
await pool.connect(id);
} catch (err) {
const { code, msg } = classifyConnectFailure(err);
- throwIpcError(code, msg);
+ throwIpcError(code, redactHostLocalPaths(host.config, msg) ?? msg);
}
}
@@ -578,21 +623,181 @@ export async function ensureRemoteAgentInstalledOrInstall(
}
}
-/** Read ~/.ssh/config and seed the pool. Idempotent — subsequent calls refresh. */
-async function ensureHydrated(): Promise<void> {
- if (initPromise) return initPromise;
- initPromise = (async () => {
+function remoteConnectionFieldsChanged(left: HostConfig, right: HostConfig): boolean {
+ return left.hostname !== right.hostname
+ || left.port !== right.port
+ || left.user !== right.user
+ || effectiveAuthenticationFingerprint(left) !== effectiveAuthenticationFingerprint(right);
+}
+
+/** Compare only fields the Settings form can write before the disk re-read. */
+function editableConnectionFieldsChanged(left: HostConfig, right: HostConfig): boolean {
+ return left.hostname !== right.hostname
+ || left.port !== right.port
+ || left.user !== right.user
+ || left.authMethod !== right.authMethod
+ || left.identityFile !== right.identityFile;
+}
+
+async function readLatestSshConfigOrThrow(): Promise<ReadSshConfigResult> {
+ let result: ReadSshConfigResult;
+ try {
+ result = await readSshConfigDetailed(sshConfigPath, {
+ managedConfigPath: managedSshConfigPath,
+ });
+ } catch (error) {
+ sshConfigDiagnostic = {
+ path: sshConfigPath,
+ kind: 'io',
+ message: error instanceof Error ? error.message : String(error),
+ recoveryHint: 'Check SSH config permissions and Include paths, then refresh.',
+ };
+ log.warn('failed to read SSH config before mutation', {
+ path: sshConfigDiagnostic.path,
+ kind: sshConfigDiagnostic.kind,
+ error: sshConfigDiagnostic.message,
+ });
+ throwIpcError('SSH_CONFIG_IO_FAILED', SSH_CONFIG_READ_FAILED_MESSAGE);
+ }
+ sshConfigWarnings = result.warnings;
+ if (result.diagnostic) {
+ sshConfigDiagnostic = result.diagnostic;
+ log.warn('SSH config diagnostic before mutation', {
+ path: result.diagnostic.path,
+ kind: result.diagnostic.kind,
+ error: result.diagnostic.message,
+ });
+ throwIpcError('SSH_CONFIG_IO_FAILED', SSH_CONFIG_READ_FAILED_MESSAGE);
+ }
+ sshConfigDiagnostic = null;
+ return result;
+}
+
+async function invalidateHostRuntimeState(hostId: string): Promise<void> {
+ const oldHost = getPool().get(hostId);
+ let failure: unknown;
+ const rememberFailure = (error: unknown): void => {
+ if (failure === undefined) failure = error;
+ };
+ // Fence the file-service build before the first await. A stale probe/install
+ // must not finish against the old endpoint and republish under this alias.
+ let fileBrowserInvalidation = Promise.resolve();
+ try {
+ fileBrowserInvalidation = remoteFileBrowserEndpointInvalidator?.(hostId)
+ ?? Promise.resolve();
+ } catch (error) {
+ rememberFailure(error);
+ }
+ try {
+ invalidateRemoteCodexMcpEndpointState(hostId);
+ } catch (error) {
+ rememberFailure(error);
+ }
+ remoteAgentInstalledCache.delete(hostId);
+ clearCcManagerInstallCache(hostId);
+ invalidateRemotePiPathCaches(hostId);
+
+ const disconnectOldEndpoint = async (): Promise<void> => {
try {
- const hosts = await readSshConfig();
- await getPool().hydrate(hosts);
- log.info('ssh hosts hydrated', { count: hosts.length });
- } catch (err) {
- log.warn('failed to read ~/.ssh/config (continuing with empty pool)', {
- error: String(err),
+ await oldHost?.disconnect();
+ } catch (error) {
+ log.warn('failed to disconnect old SSH endpoint during invalidation', {
+ hostId,
+ error: error instanceof Error ? error.message : String(error),
});
- // Don't throw — empty pool is a valid starting state.
+ throw error;
}
- })();
+ };
+ // Invalidate the SSH endpoint immediately after fencing dependent builders.
+ // disconnect() advances RemoteHost's connection epoch before its first
+ // await, so ensureHostReady cannot finish an old-endpoint handshake while
+ // ancillary cleanup is still running. Closing the SSH transport also removes
+ // any server-side forwards; closeAllRemoteForwards below remains a best-effort
+ // explicit cleanup for a client that was ready at the fence boundary.
+ const earlyDisconnect = disconnectOldEndpoint();
+
+ const cleanupResults = await Promise.allSettled([
+ fileBrowserInvalidation,
+ clearAgentProxyTunnelStateAndWait(hostId),
+ oldHost?.closeAllRemoteForwards().catch((error) => {
+ log.warn('failed to clear remote forwards during endpoint invalidation', {
+ hostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }),
+ earlyDisconnect,
+ ]);
+ for (const result of cleanupResults) {
+ if (result.status === 'rejected') rememberFailure(result.reason);
+ }
+ if (failure !== undefined) throw failure;
+}
+
+async function hydrateRemoteHostsUnqueued(
+ alreadyInvalidated: ReadonlySet<string> = new Set(),
+ preserveExistingEndpoints = false,
+ requiredManagedAliases: ReadonlySet<string> = new Set(),
+): Promise<void> {
+ let result: ReadSshConfigResult;
+ try {
+ result = await readSshConfigDetailed(sshConfigPath, {
+ managedConfigPath: managedSshConfigPath,
+ });
+ } catch (error) {
+ sshConfigDiagnostic = {
+ path: sshConfigPath,
+ kind: 'io',
+ message: error instanceof Error ? error.message : String(error),
+ recoveryHint: 'Check SSH config permissions and Include paths, then refresh.',
+ };
+ throw error;
+ }
+ sshConfigWarnings = result.warnings;
+ if (result.diagnostic) {
+ sshConfigDiagnostic = result.diagnostic;
+ throw new Error(result.diagnostic.message);
+ }
+ sshConfigDiagnostic = null;
+
+ const nextById = new Map(result.hosts.map((host) => [host.id, host]));
+ const ownershipConflicts = Array.from(requiredManagedAliases).filter(
+ (alias) => nextById.get(alias)?.managedByCindy !== true,
+ );
+ if (ownershipConflicts.length > 0) {
+ throw new SshHostOwnershipConflictError(ownershipConflicts);
+ }
+ const changedOrRemoved: string[] = [];
+ for (const current of getPool().list()) {
+ const next = nextById.get(current.config.id);
+ if ((!next || remoteConnectionFieldsChanged(current.config, next))
+ && !alreadyInvalidated.has(current.config.id)) {
+ changedOrRemoved.push(current.config.id);
+ }
+ }
+ if (preserveExistingEndpoints && changedOrRemoved.length > 0) {
+ throw new Error(
+ `SSH config changed for existing aliases during add: ${changedOrRemoved.join(', ')}`,
+ );
+ }
+ await Promise.all(changedOrRemoved.map((hostId) => invalidateHostRuntimeState(hostId)));
+ await getPool().hydrate(result.hosts);
+ log.info('ssh hosts hydrated', {
+ count: result.hosts.length,
+ warnings: result.warnings.length,
+ });
+}
+
+function hydrateRemoteHosts(): Promise<void> {
+ return remoteHostHydrationQueue.run(hydrateRemoteHostsUnqueued);
+}
+
+/** Read SSH config and seed the pool. Startup/LIST never writes or repairs it. */
+async function ensureHydrated(): Promise<void> {
+ if (initPromise) return initPromise;
+ initPromise = hydrateRemoteHosts().catch((err) => {
+ log.warn('failed to read SSH config (keeping last valid pool)', { error: String(err) });
+ initPromise = null;
+ });
return initPromise;
}
@@ -603,7 +808,25 @@ async function ensureHydrated(): Promise<void> {
* agentProxy (+ tunnel 实时状态) in a single round-trip instead of having
* to call a second IPC per row.
*/
-export type HostSnapshotWithPrefs = HostSnapshot & {
+type RendererHostConfig = Pick<HostConfig,
+ | 'id'
+ | 'displayName'
+ | 'hostname'
+ | 'port'
+ | 'user'
+ | 'authMethod'
+ | 'source'
+ | 'managedByCindy'
+> & {
+ /** Renderer only needs to know whether an owned identity exists. */
+ identityFileConfigured: boolean;
+ /** Display-only basename; the absolute local path remains main-only. */
+ identityFileName?: string;
+};
+
+export type HostSnapshotWithPrefs = Omit<HostSnapshot, 'config' | 'lastError'> & {
+ config: RendererHostConfig;
+ lastError?: string;
autoConnect: boolean;
/** 未开启 / 未配置 → null。 */
agentProxy: SshHostAgentProxyPref | null;
@@ -611,16 +834,63 @@ export type HostSnapshotWithPrefs = HostSnapshot & {
agentProxyTunnel: AgentProxyTunnelState | null;
};
+function portableBasename(value: string): string {
+ const index = Math.max(value.lastIndexOf('/'), value.lastIndexOf('\\'));
+ return index >= 0 ? value.slice(index + 1) : value;
+}
+
+/** Remove main-only local paths before a status or error crosses IPC. */
+function redactHostLocalPaths(config: HostConfig, message: string | undefined): string | undefined {
+ if (!message) return message;
+ return redactSshSensitiveText(config, message);
+}
+
+function toRendererHostConfig(config: HostConfig): RendererHostConfig {
+ return {
+ id: config.id,
+ ...(config.displayName !== undefined ? { displayName: config.displayName } : {}),
+ hostname: config.hostname,
+ port: config.port,
+ user: config.user,
+ authMethod: config.authMethod,
+ identityFileConfigured: config.identityFile !== undefined,
+ ...(config.identityFile !== undefined
+ ? { identityFileName: portableBasename(config.identityFile) }
+ : {}),
+ source: config.source,
+ managedByCindy: config.managedByCindy,
+ };
+}
+
function withPrefs(snapshot: HostSnapshot): HostSnapshotWithPrefs {
const id = snapshot.config.id;
return {
...snapshot,
+ config: {
+ ...toRendererHostConfig(snapshot.config),
+ displayName: getSshHostDisplayName(id),
+ },
+ ...(snapshot.lastError
+ ? { lastError: redactHostLocalPaths(snapshot.config, snapshot.lastError) }
+ : {}),
autoConnect: getSshHostAutoConnect(id),
agentProxy: getSshHostAgentProxy(id),
agentProxyTunnel: getAgentProxyTunnelState(id),
};
}
+function currentRemoteSshListResult(): {
+ hosts: HostSnapshotWithPrefs[];
+ warningCount: number;
+ diagnostic: Pick<SshConfigDiagnostic, 'kind'> | null;
+} {
+ return {
+ hosts: getPool().list().map(withPrefs),
+ warningCount: sshConfigWarnings.length,
+ diagnostic: sshConfigDiagnostic ? { kind: sshConfigDiagnostic.kind } : null,
+ };
+}
+
function broadcastStatus(snapshot: HostSnapshot): void {
const payload = withPrefs(snapshot);
for (const win of BrowserWindow.getAllWindows()) {
@@ -668,15 +938,36 @@ function normalizeAgentProxyInput(raw: unknown): SshHostAgentProxyPref | null |
return { enabled: true, mode: 'tunnel', localHost, localPort, remotePort: remotePortRaw };
}
-function normalizeAddInput(raw: unknown): AddHostInput & { agentProxy?: SshHostAgentProxyPref | null } {
+function normalizeAddInput(
+ raw: unknown,
+ options: { allowIdentityFileUnchanged?: boolean } = {},
+): AddHostInput & {
+ displayName: string;
+ identityFileUnchanged: boolean;
+ agentProxy?: SshHostAgentProxyPref | null;
+} {
const obj = requireObject(raw, 'host');
const id = requireString(obj.id, 'id').trim();
- // Alias must be safe to drop into ~/.ssh/config Host directive.
- if (/\s/.test(id) || id.includes('*') || id.includes('?') || id.startsWith('!')) {
- throwIpcError('INVALID_PARAMS', 'id must not contain whitespace or wildcards');
+ // Alias must be safe to drop into Cindy's managed OpenSSH Host directive.
+ if (!id
+ || /[\s\0]/.test(id)
+ || id.includes('*')
+ || id.includes('?')
+ || id.includes('[')
+ || id.startsWith('!')) {
+ throwIpcError('INVALID_PARAMS', 'id must not contain whitespace or SSH pattern characters');
}
const hostname = requireString(obj.hostname, 'hostname').trim();
+ if (!hostname || /[\s\0]/.test(hostname)) {
+ throwIpcError('INVALID_PARAMS', 'hostname must be a non-empty SSH host without whitespace');
+ }
+ const displayName = typeof obj.displayName === 'string' && obj.displayName.trim()
+ ? obj.displayName.trim()
+ : id;
const user = requireString(obj.user, 'user').trim();
+ if (!user || /[\s\0]/.test(user)) {
+ throwIpcError('INVALID_PARAMS', 'user must be a non-empty SSH user without whitespace');
+ }
const port = typeof obj.port === 'number' && Number.isInteger(obj.port) && obj.port > 0 && obj.port < 65536
? obj.port
: 22;
@@ -688,11 +979,132 @@ function normalizeAddInput(raw: unknown): AddHostInput & { agentProxy?: SshHostA
const identityFile = typeof obj.identityFile === 'string' && obj.identityFile.trim()
? expandHome(obj.identityFile.trim())
: undefined;
- if (authMethod === 'key' && !identityFile) {
+ const identityFileUnchanged = obj.identityFileUnchanged === true;
+ if (identityFileUnchanged && !options.allowIdentityFileUnchanged) {
+ throwIpcError('INVALID_PARAMS', 'identityFileUnchanged is only valid when updating a host');
+ }
+ if (identityFileUnchanged && identityFile !== undefined) {
+ throwIpcError('INVALID_PARAMS', 'identityFile and identityFileUnchanged are mutually exclusive');
+ }
+ if (identityFile && /[\0\r\n]/.test(identityFile)) {
+ throwIpcError('INVALID_PARAMS', 'identityFile must not contain NUL or line breaks');
+ }
+ if (authMethod === 'key' && !identityFile && !identityFileUnchanged) {
throwIpcError('INVALID_PARAMS', 'identityFile required when authMethod is "key"');
}
const agentProxy = normalizeAgentProxyInput(obj.agentProxy);
- return { id, hostname, port, user, authMethod, identityFile, ...(agentProxy !== undefined ? { agentProxy } : {}) };
+ return {
+ id,
+ displayName,
+ hostname,
+ port,
+ user,
+ authMethod,
+ identityFile,
+ identityFileUnchanged,
+ ...(agentProxy !== undefined ? { agentProxy } : {}),
+ };
+}
+
+async function assertHostHasNoSessionReferences(
+ id: string,
+ action: '修改' | '删除',
+): Promise<void> {
+ try {
+ const refs = await getDbClient().drizzle
+ .select({ id: sessions.id })
+ .from(sessions)
+ .where(eq(sessions.remoteHostId, id))
+ .limit(1);
+ if (refs.length > 0) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ action === '修改'
+ ? `host "${id}" 仍被远端会话引用 — 修改连接字段会重定向到新机器, 请先迁移这些会话, 或保留原配置`
+ : `host "${id}" 仍被远端会话引用 — 请先在设置中迁移这些会话, 或保留该 host`,
+ );
+ }
+ } catch (error) {
+ if ((error as { code?: string }).code === 'PRECONDITION_FAILED') throw error;
+ const rawCode = (error as { code?: unknown }).code;
+ const safeCode = typeof rawCode === 'string' && /^[A-Z0-9_]{1,64}$/.test(rawCode)
+ ? rawCode
+ : undefined;
+ log.warn('SSH host reference check failed', {
+ hostId: id,
+ action,
+ errorType: error instanceof Error ? error.name : typeof error,
+ ...(safeCode ? { errorCode: safeCode } : {}),
+ });
+ throwIpcError(
+ 'INTERNAL',
+ 'Unable to verify whether this SSH host is in use. No changes were made; please retry.',
+ );
+ }
+}
+
+function managedWriteTokenOrThrow(result: ReadSshConfigResult): ManagedConfigWriteToken {
+ if (result.managedConfigWriteToken) return result.managedConfigWriteToken;
+ log.warn('managed SSH config preflight produced no write token', {
+ errorType: 'contract',
+ });
+ throwIpcError('INTERNAL', 'Unable to prepare a safe SSH configuration update. No changes were made.');
+}
+
+function throwManagedConfigWriteError(action: 'update' | 'remove', error: unknown): never {
+ const code = (error as { code?: unknown }).code;
+ log.warn('managed SSH config write failed', {
+ action,
+ errorType: error instanceof Error ? error.name : typeof error,
+ ...(typeof code === 'string' && /^[A-Z0-9_]{1,64}$/.test(code)
+ ? { errorCode: code }
+ : {}),
+ });
+ if (code === MANAGED_CONFIG_CONCURRENT_MODIFICATION_CODE) {
+ throwIpcError(
+ 'SSH_CONFIG_CONCURRENT_MODIFICATION',
+ 'The SSH configuration changed on disk. Reload it and try again.',
+ );
+ }
+ if (code === MANAGED_CONFIG_OWNERSHIP_REQUIRED_CODE) {
+ throwIpcError(
+ 'SSH_CONFIG_OWNERSHIP_REQUIRED',
+ 'The existing Cindy SSH config is not owned by Cindy; add the ownership marker or choose another file.',
+ );
+ }
+ if (code === MANAGED_CONFIG_WRITE_TOKEN_REQUIRED_CODE) {
+ throwIpcError('INTERNAL', 'Unable to prepare a safe SSH configuration update. No changes were made.');
+ }
+ throwIpcError('SSH_CONFIG_IO_FAILED', SSH_CONFIG_WRITE_FAILED_MESSAGE);
+}
+
+function throwReloadRequired(action: string, error: unknown): never {
+ log.warn('SSH config mutation committed but refresh failed', {
+ action,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throwIpcError(
+ 'SSH_CONFIG_RELOAD_REQUIRED',
+ `${action}已写入 SSH 配置,但 Cindy 刷新失败;请重新加载 SSH 配置。`,
+ );
+}
+
+function patchSshHostPrefOrThrow(
+ hostId: string,
+ patch: Parameters<typeof patchSshHostPref>[1],
+): void {
+ try {
+ patchSshHostPref(hostId, patch);
+ } catch (error) {
+ log.warn('SSH host local preferences could not be saved', {
+ hostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throwIpcError(
+ 'SSH_HOST_PREFS_WRITE_FAILED',
+ 'The SSH host remains available, but local display-name or Agent Proxy preferences were not saved.',
+ );
+ }
}
export function registerRemoteSshIpc(): void {
@@ -730,259 +1142,266 @@ export function registerRemoteSshIpc(): void {
getMainHost: (hostId) => getPool().get(hostId) ?? null,
});
- ipcMain.handle(REMOTE_SSH_INVOKE.LIST, async () => {
+ ipcMain.handle(REMOTE_SSH_INVOKE.LIST, async (event) => {
+ assertTrustedAppRendererEvent(event);
await ensureHydrated();
- return { hosts: getPool().list().map(withPrefs) };
+ return currentRemoteSshListResult();
});
- ipcMain.handle(REMOTE_SSH_INVOKE.RELOAD_CONFIG, async () => {
+ ipcMain.handle(REMOTE_SSH_INVOKE.RELOAD_CONFIG, async (event) => {
+ assertTrustedAppRendererEvent(event);
try {
- const hosts = await readSshConfig();
- await getPool().hydrate(hosts);
- return { hosts: getPool().list().map(withPrefs) };
+ await hydrateRemoteHosts();
} catch (err) {
- throwIpcError('SSH_CONFIG_IO_FAILED', `read ~/.ssh/config failed: ${String(err)}`);
+ log.warn('failed to reload SSH config', { error: String(err) });
}
+ return currentRemoteSshListResult();
});
- ipcMain.handle(REMOTE_SSH_INVOKE.ADD, async (_event, rawHost: unknown) => {
+ ipcMain.handle(REMOTE_SSH_INVOKE.ADD, async (event, rawHost: unknown) => {
+ assertTrustedAppRendererEvent(event);
const input = normalizeAddInput(rawHost);
- const cfg: HostConfig = {
- id: input.id,
- hostname: input.hostname,
- port: input.port ?? 22,
- user: input.user,
- authMethod: input.authMethod ?? 'agent',
- identityFile: input.identityFile,
- source: 'manual',
- };
-
- const existing = getPool().get(cfg.id);
- if (existing) {
- throwIpcError('ALREADY_EXISTS', `host already exists: ${cfg.id}`);
- }
-
- try {
- await upsertHost(cfg);
- } catch (err) {
- throwIpcError('SSH_CONFIG_IO_FAILED', `write ~/.ssh/config failed: ${String(err)}`);
- }
-
- const host = getPool().add(cfg);
- if (input.agentProxy !== undefined) {
- setSshHostAgentProxy(cfg.id, input.agentProxy);
- }
- // 轮 40-w4-t8 HIGH:host 配置变更(凭证/端点相关)成功路径需审计。
- log.info('audit: remote ssh host added', {
- operation: 'remote_ssh_host_add',
- hostId: cfg.id,
- hostname: cfg.hostname,
- user: cfg.user,
- port: cfg.port ?? null,
- authMethod: cfg.authMethod ?? null,
+ await ensureHydrated();
+ return remoteHostHydrationQueue.run(async () => {
+ if (getPool().get(input.id)) {
+ throwIpcError('ALREADY_EXISTS', `host already exists: ${input.id}`);
+ }
+ const latest = await readLatestSshConfigOrThrow();
+ if (latest.hosts.some((host) => host.id === input.id)) {
+ throwIpcError('ALREADY_EXISTS', `host already exists: ${input.id}`);
+ }
+ const cfg: HostConfig = {
+ id: input.id,
+ hostname: input.hostname,
+ port: input.port ?? 22,
+ user: input.user,
+ authMethod: input.authMethod ?? 'agent',
+ identityFile: input.identityFile,
+ source: 'ssh-config',
+ managedByCindy: true,
+ };
+ let addReceipt: ManagedHostAddReceipt;
+ try {
+ addReceipt = await addManagedHostWithInclude(cfg, sshConfigPath, managedSshConfigPath);
+ } catch (err) {
+ log.warn('failed to write SSH config while adding host', { error: String(err) });
+ if ((err as { code?: string }).code === MANAGED_CONFIG_OWNERSHIP_REQUIRED_CODE) {
+ throwIpcError(
+ 'SSH_CONFIG_OWNERSHIP_REQUIRED',
+ 'The existing Cindy SSH config is not owned by Cindy; add the ownership marker or choose another file.',
+ );
+ }
+ throwIpcError('SSH_CONFIG_IO_FAILED', SSH_CONFIG_WRITE_FAILED_MESSAGE);
+ }
+ let refreshError: unknown;
+ try {
+ // ADD must not disconnect or repoint any existing alias. If an external
+ // editor changed one concurrently, keep the old pool and ask for an
+ // explicit reload. A collision on the newly-added alias is handled
+ // separately and conditionally rolls back Cindy's staged block.
+ await hydrateRemoteHostsUnqueued(new Set(), true, new Set([cfg.id]));
+ } catch (err) {
+ if (err instanceof SshHostOwnershipConflictError) {
+ let rolledBack = false;
+ let rollbackError: unknown;
+ try {
+ rolledBack = await addReceipt.rollback();
+ } catch (error) {
+ rollbackError = error;
+ }
+ log.warn('SSH host ownership changed while adding', {
+ hostId: cfg.id,
+ rolledBack,
+ ...(rollbackError !== undefined
+ ? {
+ rollbackError: rollbackError instanceof Error
+ ? rollbackError.message
+ : String(rollbackError),
+ }
+ : {}),
+ });
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'SSH configuration changed while adding the host; reload it and try again.',
+ );
+ }
+ refreshError = err;
+ }
+ // The managed host is already committed. Persist alias-local fields even
+ // when the in-memory refresh failed so the subsequent reload does not
+ // silently lose the form's display name or Agent Proxy choice.
+ patchSshHostPrefOrThrow(cfg.id, {
+ displayName: input.displayName,
+ ...(input.agentProxy !== undefined ? { agentProxy: input.agentProxy } : {}),
+ });
+ if (refreshError !== undefined) {
+ // ADD never disconnects existing aliases. The new host remains on disk
+ // and becomes visible after a successful explicit reload.
+ throwReloadRequired('新主机', refreshError);
+ }
+ const host = getPool().get(cfg.id);
+ if (!host) throwReloadRequired('新主机', new Error('host missing after refresh'));
+ log.info('audit: remote ssh host added', {
+ operation: 'remote_ssh_host_add',
+ hostId: cfg.id,
+ hostname: cfg.hostname,
+ user: cfg.user,
+ port: cfg.port,
+ authMethod: cfg.authMethod,
+ });
+ return { host: withPrefs(host.snapshot()) };
});
- return { host: withPrefs(host.snapshot()) };
});
- ipcMain.handle(REMOTE_SSH_INVOKE.UPDATE, async (_event, rawHost: unknown) => {
- const input = normalizeAddInput(rawHost);
- const existing = getPool().get(input.id);
- if (!existing) {
- throwIpcError('SSH_HOST_NOT_FOUND', `unknown host: ${input.id}`);
- }
- // Edit is allowed regardless of source. We update only the directives
- // xdt-maker owns (HostName / User / Port / IdentityFile / IdentitiesOnly)
- // and leave everything else in the block (ProxyJump / ServerAliveInterval /
- // comments / ...) untouched — see updateHostFields. `source` is a
- // disk-vs-UI provenance hint only; after a restart, hydrate() flips
- // every host back to 'ssh-config' so the old "manual only" gate
- // would lock out everything the user had just added.
- const cfg: HostConfig = {
- id: input.id,
- hostname: input.hostname,
- port: input.port ?? 22,
- user: input.user,
- authMethod: input.authMethod ?? 'agent',
- identityFile: input.identityFile,
- // Preserve original source — editing doesn't change provenance.
- source: existing.config.source,
- };
-
- // 仅当连接字段真的变了才断开 — 只改 agentProxy 偏好不该打断正在用的
- // SSH 连接 (隧道/会话都在上面)。
- const prev = existing.config;
- const connectionFieldsChanged =
- prev.hostname !== cfg.hostname ||
- prev.user !== cfg.user ||
- prev.port !== cfg.port ||
- prev.authMethod !== cfg.authMethod ||
- prev.identityFile !== cfg.identityFile;
- // 轮 42 P1(codex-connector):引用检查必须在 disconnect **之前** ——
- // 有活跃会话时编辑被拒绝, 但断开已发生会中断正在用的会话/隧道。
- if (connectionFieldsChanged) {
- try {
- const db = getDbClient().drizzle;
- const refs = await db
- .select({ id: sessions.id })
- .from(sessions)
- .where(eq(sessions.remoteHostId, input.id))
- .limit(1);
- if (refs.length > 0) {
+ ipcMain.handle(REMOTE_SSH_INVOKE.UPDATE, async (event, rawHost: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const input = normalizeAddInput(rawHost, { allowIdentityFileUnchanged: true });
+ await ensureHydrated();
+ return remoteHostHydrationQueue.run(async () => {
+ const existing = getPool().get(input.id);
+ if (!existing) throwIpcError('SSH_HOST_NOT_FOUND', `unknown host: ${input.id}`);
+ if (input.identityFileUnchanged && !existing.config.identityFile) {
+ throwIpcError('INVALID_PARAMS', 'host has no existing identityFile to preserve');
+ }
+ const cfg: HostConfig = {
+ id: input.id,
+ hostname: input.hostname,
+ port: input.port ?? 22,
+ user: input.user,
+ authMethod: input.authMethod ?? 'agent',
+ identityFile: input.identityFileUnchanged
+ ? existing.config.identityFile
+ : input.identityFile,
+ source: 'ssh-config',
+ managedByCindy: existing.config.managedByCindy,
+ };
+ const connectionFieldsChanged = editableConnectionFieldsChanged(existing.config, cfg);
+ let managedWriteToken: ManagedConfigWriteToken | undefined;
+ if (connectionFieldsChanged) {
+ const latest = await readLatestSshConfigOrThrow();
+ const latestHost = latest.hosts.find((host) => host.id === input.id);
+ if (!latestHost?.managedByCindy) {
+ throwIpcError(
+ 'SSH_CONFIG_OWNERSHIP_REQUIRED',
+ 'This SSH host is no longer uniquely managed by Cindy. Reload the SSH configuration before editing.',
+ );
+ }
+ if (remoteConnectionFieldsChanged(existing.config, latestHost)) {
throwIpcError(
'PRECONDITION_FAILED',
- `host "${input.id}" 仍被远端会话引用 — 修改连接字段会重定向到新机器, 请先迁移这些会话, 或保留原配置`,
+ `host "${input.id}" changed on disk; reload before editing`,
);
}
- } catch (err) {
- if ((err as { code?: string })?.code === 'PRECONDITION_FAILED') throw err;
- throwIpcError(
- 'INTERNAL',
- `host "${input.id}" 引用检查失败, 未修改 — 请重试: ${err instanceof Error ? err.message : String(err)}`,
- );
+ managedWriteToken = managedWriteTokenOrThrow(latest);
+ cfg.managedByCindy = true;
}
- }
- // 轮 42 P1(codex-connector):旧 host 的 Pi daemon 清理必须在 disconnect
- // **之前** —— cleanupRemotePiDaemonsOnHost 内部用 RemoteHost.exec()
- // (piManagerList/probe), exec 立即 requireReady(), 断开的 host 会抛错。
- // 顺序: 引用检查 → 清理旧 daemon(连接还在) → 清 cache → disconnect。
- if (connectionFieldsChanged) {
- // 无活跃会话引用 → 清理旧 host 的 Pi daemon(含凭证 env-file)。
- if (existing.getStatus() === 'ready') {
- await cleanupRemotePiDaemonsOnHost(existing).catch(() => undefined);
- }
- remoteAgentInstalledCache.delete(input.id);
- clearCcManagerInstallCache(input.id);
- invalidateRemotePiPathCaches(input.id);
- }
- if (connectionFieldsChanged && existing.getStatus() !== 'disconnected') {
- await existing.disconnect();
- }
+ if (connectionFieldsChanged) await assertHostHasNoSessionReferences(input.id, '修改');
- try {
- await updateHostFields(cfg);
- } catch (err) {
- throwIpcError('SSH_CONFIG_IO_FAILED', `update ~/.ssh/config failed: ${String(err)}`);
- }
- existing.updateConfig(cfg);
-
- // agentProxy 偏好: 写盘 + host 活着就立即应用 (建/拆隧道 + codex daemon
- // env 对账)。host 未连时只落 pref, 下次 ready 时由 ready hook 应用。
- if (input.agentProxy !== undefined) {
- setSshHostAgentProxy(cfg.id, input.agentProxy);
- if (existing.getStatus() === 'ready') {
- await applyAgentProxyForHost(existing);
+ if (connectionFieldsChanged) {
+ let refreshError: unknown;
+ try {
+ await updateManagedHostFields(cfg, managedSshConfigPath, managedWriteToken!);
+ } catch (err) {
+ // The live connection remains untouched until the managed write has
+ // committed successfully.
+ throwManagedConfigWriteError('update', err);
+ }
+ try {
+ if (existing.getStatus() === 'ready') {
+ await cleanupRemotePiDaemonsOnHost(existing).catch(() => undefined);
+ }
+ await invalidateHostRuntimeState(input.id);
+ await hydrateRemoteHostsUnqueued(new Set([input.id]));
+ } catch (err) {
+ refreshError = err;
+ }
+ patchSshHostPrefOrThrow(cfg.id, {
+ displayName: input.displayName,
+ ...(input.agentProxy !== undefined ? { agentProxy: input.agentProxy } : {}),
+ });
+ if (refreshError !== undefined) throwReloadRequired('主机修改', refreshError);
+ } else {
+ patchSshHostPrefOrThrow(cfg.id, {
+ displayName: input.displayName,
+ ...(input.agentProxy !== undefined ? { agentProxy: input.agentProxy } : {}),
+ });
}
- }
- // 轮 40-w4-t8 HIGH:update(端点/凭证字段可能变更)成功路径需审计。
- log.info('audit: remote ssh host updated', {
- operation: 'remote_ssh_host_update',
- hostId: cfg.id,
- connectionFieldsChanged,
- hostname: cfg.hostname,
- user: cfg.user,
- port: cfg.port ?? null,
- authMethod: cfg.authMethod ?? null,
+ const refreshed = getPool().get(cfg.id);
+ if (!refreshed) throwReloadRequired('主机修改', new Error('host missing after refresh'));
+ if (!connectionFieldsChanged && input.agentProxy !== undefined && refreshed.getStatus() === 'ready') {
+ await applyAgentProxyForHost(refreshed);
+ }
+ log.info('audit: remote ssh host updated', {
+ operation: 'remote_ssh_host_update',
+ hostId: cfg.id,
+ connectionFieldsChanged,
+ hostname: cfg.hostname,
+ user: cfg.user,
+ port: cfg.port,
+ authMethod: cfg.authMethod,
+ });
+ return { host: withPrefs(refreshed.snapshot()) };
});
- return { host: withPrefs(existing.snapshot()) };
});
- ipcMain.handle(REMOTE_SSH_INVOKE.REMOVE, async (_event, args: unknown) => {
+ ipcMain.handle(REMOTE_SSH_INVOKE.REMOVE, async (event, args: unknown) => {
+ assertTrustedAppRendererEvent(event);
const obj = requireObject(args);
const id = requireString(obj.id, 'id');
-
- const host = getPool().get(id);
- if (!host) {
- throwIpcError('SSH_HOST_NOT_FOUND', `unknown host: ${id}`);
- }
-
- // 轮 40-w4-t15 HIGH:host 被活跃 PI remote 会话引用时 fail-closed 拒绝删除
- // —— 否则 sessions.remote_host_id 悬空, 会话永久指向不可达 alias, 恢复
- // 稳定失败(UI 建议的 remove+readd 改名路径正是踩这个坑)。提示用户先迁移
- // 会话或保留该 host。
- try {
- const db = getDbClient().drizzle;
- const refs = await db
- .select({ id: sessions.id })
- .from(sessions)
- .where(eq(sessions.remoteHostId, id))
- .limit(1);
- if (refs.length > 0) {
+ await ensureHydrated();
+ return remoteHostHydrationQueue.run(async () => {
+ const host = getPool().get(id);
+ if (!host) throwIpcError('SSH_HOST_NOT_FOUND', `unknown host: ${id}`);
+ const latest = await readLatestSshConfigOrThrow();
+ const latestHost = latest.hosts.find((candidate) => candidate.id === id);
+ if (!latestHost?.managedByCindy) {
throwIpcError(
- 'PRECONDITION_FAILED',
- `host "${id}" 仍被远端会话引用 — 请先在设置中迁移这些会话, 或保留该 host`,
+ 'SSH_CONFIG_OWNERSHIP_REQUIRED',
+ 'This SSH host is no longer uniquely managed by Cindy. Reload the SSH configuration before removing it.',
);
}
- } catch (err) {
- if ((err as { code?: string })?.code === 'PRECONDITION_FAILED') throw err;
- // 轮 42 P2(codex-connector):DB 查询失败也 fail-closed —— 无法证明没有
- // 会话引用该 host 时继续删, 会留下悬空 remote_host_id(会话永久不可恢复)。
- // 查询失败 ≠ 可以跳过引用守卫; 报错让用户重试(删错不可逆, 删不了可重试)。
- throwIpcError(
- 'INTERNAL',
- `host "${id}" 引用检查失败, 未删除 — 请重试: ${err instanceof Error ? err.message : String(err)}`,
- );
- }
-
- // Only strip the config block when the host was added via maker. Hosts
- // imported from existing ~/.ssh/config are left intact — the user owns
- // that file; we don't yank entries they wrote themselves.
- if (host.config.source === 'manual') {
+ const managedWriteToken = managedWriteTokenOrThrow(latest);
+ await assertHostHasNoSessionReferences(id, '删除');
+ let refreshError: unknown;
try {
- await removeHostFromConfig(id);
+ await removeManagedHost(id, managedSshConfigPath, managedWriteToken);
} catch (err) {
- throwIpcError('SSH_CONFIG_IO_FAILED', `strip ~/.ssh/config failed: ${String(err)}`);
+ throwManagedConfigWriteError('remove', err);
}
- }
-
- // 清理远端 pi daemon 会话(host 移除后 setsid daemon 仍会跑,孤儿进程 —
- // R1 安装 M4)。**必须在 getPool().remove(id) 之前** —— remove 后 pool 里
- // 拿不到 host, 清理永不执行(R4-4 问题 2: 之前的实现是死代码)。
- // best-effort:daemon 脚本未上传/未连接则跳过。
- if (host.getStatus() === 'ready') {
try {
- // host remove 前先 soft-close 该 host 上活跃的 pi 会话:直接 kill
- // daemon 会让本地 session 收到"意外退出"式 error, 干净关闭避免
- // crash-like UX(R6 审计 M-10, 对齐 CC 的 softCloseCcSessionsForHost)。
- await softClosePiSessionsForHost(id);
+ if (host.getStatus() === 'ready') {
+ await softClosePiSessionsForHost(id).catch(() => undefined);
+ await cleanupRemotePiDaemonsOnHost(host).catch(() => undefined);
+ }
+ await invalidateHostRuntimeState(id);
+ await hydrateRemoteHostsUnqueued(new Set([id]));
} catch (err) {
- log.warn('pi session soft-close before host remove failed (non-fatal)', {
- hostId: id,
- error: err instanceof Error ? err.message : String(err),
- });
+ refreshError = err;
}
- try {
- await cleanupRemotePiDaemonsOnHost(host);
- } catch (err) {
- log.warn('pi daemon cleanup on host remove failed (non-fatal)', {
- hostId: id,
- error: String((err as Error)?.message ?? err),
- });
+ // Disk no longer contains Cindy's alias. Cleanup is alias-scoped and
+ // cannot be retried through REMOVE after the next reload, so always run
+ // every cleanup action before surfacing a refresh failure.
+ for (const cleanup of [
+ () => removeSshHostPref(id),
+ () => clearAgentProxyTunnelState(id),
+ () => removeRemoteMcpForwardPref(id),
+ ]) {
+ try {
+ cleanup();
+ } catch (error) {
+ log.warn('failed to clean removed SSH host local state', {
+ hostId: id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
}
- } else {
- // host 已断开:kill 命令发不出去, 残留由 daemon 空闲超时兜底回收
- // (R6 审计 F7/M-5 —— 不能静默, 留日志便于诊断)。
- log.warn('host not connected — pi daemon cleanup skipped; remote daemons will be reclaimed by idle timeout', {
+ if (refreshError !== undefined) throwReloadRequired('主机删除', refreshError);
+ log.info('audit: remote ssh host removed', {
+ operation: 'remote_ssh_host_remove',
hostId: id,
});
- }
- await getPool().remove(id);
- // 同步清掉 prefs 里的孤儿 autoConnect 标志, 避免后续重新 add 同名 host 时
- // 拿到旧偏好造成"莫名其妙又自动连了"。同步清 agent install cache、agent
- // proxy 隧道状态与 per-host MCP 转发端口记录。
- removeSshHostPref(id);
- clearAgentProxyTunnelState(id);
- removeRemoteMcpForwardPref(id);
- remoteAgentInstalledCache.delete(id);
- clearCcManagerInstallCache(id);
- // 轮 40-w4-t4 MEDIUM:清 pi 远端路径 cache —— 否则同名 host 重建(不同
- // user/home/port)会串到旧远端路径。
- invalidateRemotePiPathCaches(id);
- // 轮 40-w4-t8 HIGH:host 移除(剥离配置 + 清理 daemon)成功路径需审计。
- log.info('audit: remote ssh host removed', {
- operation: 'remote_ssh_host_remove',
- hostId: id,
+ return { ok: true as const };
});
- return { ok: true as const };
});
ipcMain.handle(REMOTE_SSH_INVOKE.CONNECT, async (_event, args: unknown) => {
@@ -1002,10 +1421,11 @@ export function registerRemoteSshIpc(): void {
// text (ssh-copy-id hint) verbatim so the toast matches the host-row
// subtitle; a local identityFile ENOENT is classified off `.code`.
const { code, msg } = classifyConnectFailure(err);
- throwIpcError(code, msg);
+ throwIpcError(code, redactHostLocalPaths(host.config, msg) ?? msg);
}
- return { host: getPool().get(id)?.snapshot() ?? null };
+ const connected = getPool().get(id);
+ return { host: connected ? withPrefs(connected.snapshot()) : null };
});
ipcMain.handle(REMOTE_SSH_INVOKE.DISCONNECT, async (_event, args: unknown) => {
@@ -1044,7 +1464,8 @@ export function registerRemoteSshIpc(): void {
}
}
await getPool().disconnect(id);
- return { host: getPool().get(id)?.snapshot() ?? null };
+ const disconnected = getPool().get(id);
+ return { host: disconnected ? withPrefs(disconnected.snapshot()) : null };
});
// ── Phase B: agent on remote ─────────────────────────────────────────────
diff --git a/apps/desktop/src/main/remote-ssh/ssh-host-prefs-store.ts b/apps/desktop/src/main/remote-ssh/ssh-host-prefs-store.ts
index 3dfea7a3af..61e6de86ec 100644
--- a/apps/desktop/src/main/remote-ssh/ssh-host-prefs-store.ts
+++ b/apps/desktop/src/main/remote-ssh/ssh-host-prefs-store.ts
@@ -1,5 +1,6 @@
/**
- * ssh-host-prefs-store —— 每台 SSH 远端机器的本地偏好(autoConnect + agentProxy)。
+ * ssh-host-prefs-store —— 每台 SSH 远端机器的本地偏好(displayName +
+ * autoConnect + agentProxy)。
*
* 设计上跟 ~/.ssh/config 解耦: 不污染用户的 ssh config (那是 ssh 客户端通用配置),
* 用一个独立 JSON 落 <userData>/ssh-host-prefs.json. 数据极小, 同步 R/W + 内存
@@ -55,6 +56,7 @@ export function isAllowedAgentProxyRemotePort(v: unknown): v is number {
}
export interface SshHostPref {
+ displayName?: string;
autoConnect: boolean;
agentProxy?: SshHostAgentProxyPref;
}
@@ -114,6 +116,9 @@ function normalize(raw: unknown): SshHostPrefs {
const v = value as Record<string, unknown>;
const agentProxy = normalizeAgentProxy(v.agentProxy);
out[hostId] = {
+ ...(typeof v.displayName === 'string' && v.displayName.trim()
+ ? { displayName: v.displayName.trim() }
+ : {}),
autoConnect: v.autoConnect === true,
...(agentProxy ? { agentProxy } : {}),
};
@@ -121,6 +126,14 @@ function normalize(raw: unknown): SshHostPrefs {
return out;
}
+export function getSshHostDisplayName(hostId: string): string {
+ return readSshHostPrefs()[hostId]?.displayName?.trim() || hostId;
+}
+
+export function setSshHostDisplayName(hostId: string, displayName: string): void {
+ patchSshHostPref(hostId, { displayName });
+}
+
let cached: SshHostPrefs | null = null;
/** 同步读取全部 prefs, 第一次从盘读, 后续走 cache. */
@@ -159,21 +172,45 @@ export function getSshHostAgentProxy(hostId: string): SshHostAgentProxyPref | nu
/** 写入单 host 的 agentProxy 配置 (null = 关闭并清除), atomic write + 更新 cache. */
export function setSshHostAgentProxy(hostId: string, agentProxy: SshHostAgentProxyPref | null): void {
+ patchSshHostPref(hostId, { agentProxy });
+}
+
+/** Persist related alias-local fields in one atomic prefs-file replacement. */
+export function patchSshHostPref(
+ hostId: string,
+ patch: { displayName?: string; agentProxy?: SshHostAgentProxyPref | null },
+): void {
const current = { ...readSshHostPrefs() };
- // 不 spread 旧 entry — 旧 agentProxy 会借 spread 复活, null 语义就是清除。
- const next: SshHostPref = { autoConnect: current[hostId]?.autoConnect === true };
- if (agentProxy) {
- const normalized = normalizeAgentProxy(agentProxy);
- if (!normalized) {
- throw new Error(`invalid agentProxy pref: localHost/localPort malformed`);
+ const next: SshHostPref = {
+ autoConnect: current[hostId]?.autoConnect === true,
+ ...(current[hostId]?.displayName ? { displayName: current[hostId].displayName } : {}),
+ ...(current[hostId]?.agentProxy ? { agentProxy: current[hostId].agentProxy } : {}),
+ };
+
+ if (patch.displayName !== undefined) {
+ const normalized = patch.displayName.trim();
+ if (normalized && normalized !== hostId) next.displayName = normalized;
+ else delete next.displayName;
+ }
+
+ if (patch.agentProxy !== undefined) {
+ // null explicitly clears; undefined means the caller did not edit this field.
+ delete next.agentProxy;
+ if (patch.agentProxy) {
+ const normalized = normalizeAgentProxy(patch.agentProxy);
+ if (!normalized) {
+ throw new Error('invalid agentProxy pref: localHost/localPort malformed');
+ }
+ next.agentProxy = { ...normalized, enabled: patch.agentProxy.enabled === true };
}
- next.agentProxy = { ...normalized, enabled: agentProxy.enabled === true };
}
+
current[hostId] = next;
writePrefs(current);
const ap = next.agentProxy;
- log.info('ssh host agentProxy written', {
+ log.info('ssh host local prefs written', {
hostId,
+ displayNameCustomized: !!next.displayName,
enabled: ap?.enabled === true,
mode: ap?.mode ?? null,
// 脱敏: proxyUrl 即使将来校验放宽也不原样进日志 (review: PR #992
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 360ae873eb..e0179f426f 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -4217,8 +4217,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
},
// ── Remote SSH (Phase A) ───────────────────────────────────────────────
- // 连接管理 + ~/.ssh/config IO. 暂未涉及 agent-on-remote / session 同步.
- // `host.config.id` 即 ssh alias, 与 ~/.ssh/config Host 行同名.
+ // 连接管理 + OpenSSH config 发现;Cindy 新主机写独立 managed Include 文件。
+ // `host.config.id` 即 ssh alias, 与 OpenSSH `Host` 声明同名.
remoteSsh: {
list: (): Promise<{
hosts: Array<{
@@ -4228,8 +4228,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
port: number;
user: string;
authMethod: 'agent' | 'key';
- identityFile?: string;
+ identityFileConfigured: boolean;
+ identityFileName?: string;
source: 'ssh-config' | 'manual';
+ managedByCindy: boolean;
+ displayName?: string;
};
status:
'disconnected' | 'connecting' | 'authenticating' | 'ready' | 'reconnecting' | 'failed';
@@ -4242,11 +4245,18 @@ contextBridge.exposeInMainWorld('electronAPI', {
/** 隧道实时状态 (内存态); 无记录 → null. */
agentProxyTunnel: AgentProxyTunnelState | null;
}>;
+ warningCount?: number;
+ diagnostic?: { kind: 'io' | 'syntax' | 'limit' } | null;
}> => ipcRenderer.invoke('maker:remote-ssh:list'),
- reloadConfig: (): Promise<{ hosts: unknown[] }> =>
+ reloadConfig: (): Promise<{
+ hosts: unknown[];
+ warningCount?: number;
+ diagnostic?: { kind: 'io' | 'syntax' | 'limit' } | null;
+ }> =>
ipcRenderer.invoke('maker:remote-ssh:reload-config'),
add: (host: {
id: string;
+ displayName?: string;
hostname: string;
port?: number;
user: string;
@@ -4256,11 +4266,14 @@ contextBridge.exposeInMainWorld('electronAPI', {
}): Promise<{ host: unknown }> => ipcRenderer.invoke('maker:remote-ssh:add', host),
update: (host: {
id: string;
+ displayName?: string;
hostname: string;
port?: number;
user: string;
authMethod?: 'agent' | 'key';
identityFile?: string;
+ /** Preserve the existing main-only path without returning it to Renderer. */
+ identityFileUnchanged?: boolean;
agentProxy?: SshHostAgentProxyPref | null;
}): Promise<{ host: unknown }> => ipcRenderer.invoke('maker:remote-ssh:update', host),
remove: (id: string): Promise<{ ok: true }> =>
diff --git a/apps/desktop/src/renderer/__tests__/remoteProjectIdentity.test.ts b/apps/desktop/src/renderer/__tests__/remoteProjectIdentity.test.ts
index 9488aa99d6..2a39840f0e 100644
--- a/apps/desktop/src/renderer/__tests__/remoteProjectIdentity.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteProjectIdentity.test.ts
@@ -19,7 +19,9 @@ function sshHost(
user: 'alice',
authMethod: 'agent',
source: 'ssh-config',
+ managedByCindy: false,
...overrides,
+ identityFileConfigured: overrides.identityFileConfigured ?? false,
},
status: 'ready',
statusChangedAt: 0,
@@ -53,6 +55,13 @@ describe('resolveRemoteProjectMachineIdentity', () => {
expect(identity?.displayLabel).toBe('gpu-box · [email protected]:2202');
});
+ it('shows a custom display name while retaining the SSH alias', () => {
+ const identity = resolveRemoteProjectMachineIdentity(remoteProject, [
+ sshHost('gpu-box', { displayName: 'Build box' }),
+ ]);
+ expect(identity?.displayLabel).toBe('Build box (gpu-box) · [email protected]');
+ });
+
it('falls back to the persisted remoteHostId when config is missing', () => {
expect(resolveRemoteProjectMachineIdentity(remoteProject, [])?.displayLabel).toBe('gpu-box');
});
diff --git a/apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx b/apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx
index d3518026dd..cbe556d8b3 100644
--- a/apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx
@@ -93,12 +93,18 @@ export function AddRemoteProjectDialog({
const targets = useMemo<RemoteTarget[]>(() => {
const ssh: RemoteTarget[] = excludeSsh
? []
- : sshHosts.map((h) => ({
- key: `ssh:${h.config.id}`,
- kind: 'ssh',
- hostId: h.config.id,
- label: `${h.config.id} (${h.config.user}@${h.config.hostname})`,
- }));
+ : sshHosts.map((h) => {
+ const displayName = h.config.displayName?.trim() || h.config.id;
+ const identity = displayName === h.config.id
+ ? h.config.id
+ : `${displayName} (${h.config.id})`;
+ return {
+ key: `ssh:${h.config.id}`,
+ kind: 'ssh' as const,
+ hostId: h.config.id,
+ label: `${identity} (${h.config.user}@${h.config.hostname})`,
+ };
+ });
const dev: RemoteTarget[] = devices.map((d) => ({
key: `device:${d.deviceId}`,
kind: 'device',
diff --git a/apps/desktop/src/renderer/components/settings/RemoteSection.tsx b/apps/desktop/src/renderer/components/settings/RemoteSection.tsx
index a5cd114083..851e28fc1b 100644
--- a/apps/desktop/src/renderer/components/settings/RemoteSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/RemoteSection.tsx
@@ -1,8 +1,8 @@
/**
* RemoteSection — Settings → Remote tab.
*
- * Phase A: list SSH hosts (sourced from ~/.ssh/config + ones added here),
- * connect/disconnect, add a new host, remove a manually-added host.
+ * Phase A: list SSH hosts discovered from OpenSSH config, connect/disconnect,
+ * add a Cindy-managed host, and remove a Cindy-managed host.
* No agent-on-remote yet — that's Phase B.
*
* Design: matches ConnectionsSection card layout. Inline add-form
@@ -11,7 +11,17 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Plus, Server, RefreshCw, Trash2, ChevronRight, ChevronDown, KeyRound, Pencil } from 'lucide-react';
+import {
+ AlertTriangle,
+ Plus,
+ Server,
+ RefreshCw,
+ Trash2,
+ ChevronRight,
+ ChevronDown,
+ KeyRound,
+ Pencil,
+} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from '@/lib/toast';
@@ -23,6 +33,12 @@ import { RemoteHostDetail } from './RemoteHostDetail';
import { SshKeySetupDialog } from './SshKeySetupDialog';
type Status = RemoteHostSnapshot['status'];
+type SshConfigDiagnosticKind = 'io' | 'syntax' | 'limit';
+type RemoteSshListResult = {
+ hosts: RemoteHostSnapshot[];
+ warningCount?: number;
+ diagnostic?: { kind: SshConfigDiagnosticKind } | null;
+};
interface RowProps {
snap: RemoteHostSnapshot;
@@ -73,6 +89,7 @@ function HostRow({
const disconnectable = snap.status === 'ready' || snap.status === 'connecting'
|| snap.status === 'authenticating' || snap.status === 'reconnecting';
const canExpand = snap.status === 'ready';
+ const displayName = snap.config.displayName?.trim() || snap.config.id;
// For non-failed states append " · via <auth-label>" so the user can see
// which credential is actually carrying the connection. Catches the case
@@ -119,8 +136,13 @@ function HostRow({
className="text-14 font-medium leading-tight"
style={{ color: 'var(--settings-section-title)' }}
>
- {snap.config.id}
+ {displayName}
</span>
+ {displayName !== snap.config.id && (
+ <code className="text-11" style={{ color: 'var(--settings-integration-subtitle)' }}>
+ {snap.config.id}
+ </code>
+ )}
<span
className="h-1.5 w-1.5 rounded-full"
style={{ backgroundColor: dot }}
@@ -147,6 +169,11 @@ function HostRow({
>
{subtitle}
</span>
+ {!snap.config.managedByCindy && (
+ <span className="text-11" style={{ color: 'var(--settings-integration-subtitle)' }}>
+ {t('settings.remote.readOnlyFromSshConfig')}
+ </span>
+ )}
</div>
<div className="flex items-center gap-2">
@@ -227,9 +254,8 @@ function HostRow({
<span className="relative top-px">{t('settings.remote.button.disconnect')}</span>
</button>
)}
- {/* Edit always available — surgical update preserves any hand-written
- directives (ProxyJump, ServerAliveInterval, ...) the user may
- have added in ~/.ssh/config. */}
+ {/* External hosts still expose local preferences. Main independently
+ enforces that their connection fields remain read-only. */}
<button
type="button"
onClick={onEdit}
@@ -244,7 +270,7 @@ function HostRow({
>
<Pencil size={14} />
</button>
- {snap.config.source === 'manual' && (
+ {snap.config.managedByCindy && (
<button
type="button"
onClick={onRemove}
@@ -266,11 +292,17 @@ function HostRow({
interface AddFormState {
id: string;
+ displayName: string;
hostname: string;
user: string;
port: string;
authMethod: 'agent' | 'key';
+ /** Newly entered/picked path. Existing paths remain main-only. */
identityFile: string;
+ /** Edit mode: preserve the existing main-only path until the user changes it. */
+ identityFileUnchanged: boolean;
+ /** Display-only basename for an existing configured identity. */
+ identityFileName: string;
/** 「Agent 流量走 Proxy」开关。 */
agentProxyEnabled: boolean;
/** tunnel = Cindy 代建隧道; env = 自备代理 (仅注入环境变量)。 */
@@ -287,11 +319,14 @@ const DEFAULT_AGENT_PROXY_REMOTE_PORT = String(LEGACY_AGENT_PROXY_REMOTE_PORT);
const EMPTY_FORM: AddFormState = {
id: '',
+ displayName: '',
hostname: '',
user: '',
port: '22',
authMethod: 'agent',
identityFile: '',
+ identityFileUnchanged: false,
+ identityFileName: '',
agentProxyEnabled: false,
agentProxyMode: 'tunnel',
agentProxyAddr: '127.0.0.1:7890',
@@ -375,17 +410,25 @@ interface HostFormProps {
/**
* 'add' → blank form, alias editable, submit creates a new host.
* 'edit' → form pre-filled with `initial`, alias locked (renaming is
- * rename + re-add — keeps ~/.ssh/config consistency simple),
+ * rename + re-add — keeps the OpenSSH alias join key stable),
* submit updates the existing host.
*/
mode: 'add' | 'edit';
initial?: AddFormState;
busy: boolean;
+ connectionFieldsReadOnly?: boolean;
onSubmit: (form: AddFormState) => void;
onCancel: () => void;
}
-function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
+function HostForm({
+ mode,
+ initial,
+ busy,
+ connectionFieldsReadOnly = false,
+ onSubmit,
+ onCancel,
+}: HostFormProps) {
const { t } = useTranslation();
const [form, setForm] = useState<AddFormState>(initial ?? EMPTY_FORM);
// Local dialog state. Three open modes — they share the same dialog but
@@ -399,12 +442,16 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
// Pick fills identityFile, KEEPS authMethod=agent.
const [keysOpenMode, setKeysOpenMode] = useState<'manage' | 'pick' | 'pinPick' | null>(null);
const isEdit = mode === 'edit';
+ const hasIdentityFile = form.identityFileUnchanged || form.identityFile.trim().length > 0;
+ const identityFileName = form.identityFileUnchanged
+ ? form.identityFileName
+ : form.identityFile.split(/[/\\]/).pop() ?? '';
const valid = useMemo(() => {
- if (!form.id.trim() || /\s|[*?!]/.test(form.id)) return false;
+ if (!form.id.trim() || /\s|[*?!\[]/.test(form.id)) return false;
if (!form.hostname.trim()) return false;
if (!form.user.trim()) return false;
- if (form.authMethod === 'key' && !form.identityFile.trim()) return false;
+ if (form.authMethod === 'key' && !hasIdentityFile) return false;
if (form.agentProxyEnabled) {
if (form.agentProxyMode === 'tunnel') {
if (!parseProxyAddrInput(form.agentProxyAddr)) return false;
@@ -414,7 +461,7 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
}
}
return true;
- }, [form]);
+ }, [form, hasIdentityFile]);
return (
<div
@@ -431,37 +478,52 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
</p>
<div className="grid grid-cols-2 gap-3">
+ <LabeledInput
+ label={t('settings.remote.add.displayName')}
+ placeholder={t('settings.remote.add.displayNamePlaceholder')}
+ value={form.displayName}
+ onChange={(v) => setForm({ ...form, displayName: v })}
+ />
<LabeledInput
label={t('settings.remote.add.alias')}
placeholder="my-server"
value={form.id}
onChange={(v) => setForm({ ...form, id: v })}
- // Alias / Host directive is the join key between ~/.ssh/config and
+ // Alias / Host directive is the join key between OpenSSH config and
// our pool, AND the name a user may have typed in terminal scripts.
// Renaming via UI = remove + re-add (out of scope to make safe).
- disabled={isEdit}
+ disabled={isEdit || connectionFieldsReadOnly}
/>
<LabeledInput
label={t('settings.remote.add.hostname')}
placeholder="example.com or 1.2.3.4"
value={form.hostname}
onChange={(v) => setForm({ ...form, hostname: v })}
+ disabled={connectionFieldsReadOnly}
/>
<LabeledInput
label={t('settings.remote.add.user')}
placeholder="ubuntu"
value={form.user}
onChange={(v) => setForm({ ...form, user: v })}
+ disabled={connectionFieldsReadOnly}
/>
<LabeledInput
label={t('settings.remote.add.port')}
placeholder="22"
value={form.port}
onChange={(v) => setForm({ ...form, port: v.replace(/[^0-9]/g, '') })}
+ disabled={connectionFieldsReadOnly}
/>
</div>
- <div className="flex flex-col gap-2">
+ {connectionFieldsReadOnly && (
+ <p className="text-11" style={{ color: 'var(--settings-integration-subtitle)' }}>
+ {t('settings.remote.edit.connectionFieldsReadOnly')}
+ </p>
+ )}
+
+ <div className={cn('flex flex-col gap-2', connectionFieldsReadOnly && 'hidden')}>
<label
className="text-12 font-medium"
style={{ color: 'var(--settings-section-sublabel)' }}
@@ -477,22 +539,85 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
// optional pin (FilteredAgent), in key mode it's the file we
// read directly. User can unpin / clear from the agent block.
onClick={() => setForm({ ...form, authMethod: 'agent' })}
+ disabled={connectionFieldsReadOnly}
/>
<RadioOption
checked={form.authMethod === 'key'}
label={t('settings.remote.add.auth.key')}
hint={t('settings.remote.add.auth.keyHint')}
onClick={() => setForm({ ...form, authMethod: 'key' })}
+ disabled={connectionFieldsReadOnly}
/>
</div>
{form.authMethod === 'key' && (
<div className="flex flex-col gap-1">
- <LabeledInput
- label={t('settings.remote.add.identityFile')}
- placeholder="~/.ssh/id_ed25519"
- value={form.identityFile}
- onChange={(v) => setForm({ ...form, identityFile: v })}
- />
+ {form.identityFileUnchanged ? (
+ <div className="flex flex-col gap-1">
+ <span
+ className="text-12 font-medium"
+ style={{ color: 'var(--settings-section-sublabel)' }}
+ >
+ {t('settings.remote.add.identityFile')}
+ </span>
+ <div className="flex items-center gap-2">
+ <code
+ className="flex-1 text-12 truncate rounded-md px-2 py-1.5"
+ style={{
+ backgroundColor: 'var(--surface-chip, #f5f5f5)',
+ color: 'var(--settings-section-title)',
+ fontFamily: 'var(--app-font-code, var(--app-font-code-default))',
+ }}
+ title={identityFileName}
+ >
+ {identityFileName}
+ </code>
+ <button
+ type="button"
+ onClick={() => setKeysOpenMode('pick')}
+ disabled={connectionFieldsReadOnly}
+ className="h-7 rounded-full px-3 text-12 border"
+ style={{
+ backgroundColor: 'transparent',
+ borderColor: 'var(--settings-btn-secondary-border)',
+ color: 'var(--settings-btn-secondary-text)',
+ }}
+ >
+ {t('settings.remote.add.auth.pinnedKeyChange')}
+ </button>
+ <button
+ type="button"
+ onClick={() => setForm({
+ ...form,
+ identityFile: '',
+ identityFileUnchanged: false,
+ identityFileName: '',
+ })}
+ disabled={connectionFieldsReadOnly}
+ className="h-7 rounded-full px-3 text-12 border"
+ style={{
+ backgroundColor: 'transparent',
+ borderColor: 'var(--settings-btn-secondary-border)',
+ color: 'var(--settings-btn-secondary-text)',
+ }}
+ >
+ {t('settings.remote.add.auth.pinnedKeyClear')}
+ </button>
+ </div>
+ </div>
+ ) : (
+ <LabeledInput
+ label={t('settings.remote.add.identityFile')}
+ placeholder="~/.ssh/id_ed25519"
+ value={form.identityFile}
+ onChange={(v) => setForm({
+ ...form,
+ identityFile: v,
+ identityFileUnchanged: false,
+ identityFileName: '',
+ })}
+ disabled={connectionFieldsReadOnly}
+ />
+ )}
{/* Picker shortcut — opens dialog with `pick` semantics so a
click on a key fills identityFile (instead of just browsing). */}
<div className="flex items-center gap-2 text-12">
@@ -502,6 +627,7 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
<button
type="button"
onClick={() => setKeysOpenMode('pick')}
+ disabled={connectionFieldsReadOnly}
className="inline-flex items-center gap-1 underline underline-offset-2"
style={{ color: 'var(--settings-section-title)' }}
>
@@ -523,7 +649,7 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
>
{t('settings.remote.add.auth.pinnedKeyLabel')}
</span>
- {form.identityFile ? (
+ {hasIdentityFile ? (
<div className="flex items-center gap-2">
<code
className="flex-1 text-12 truncate rounded-md px-2 py-1.5"
@@ -532,13 +658,14 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
color: 'var(--settings-section-title)',
fontFamily: 'var(--app-font-code, var(--app-font-code-default))',
}}
- title={form.identityFile}
+ title={identityFileName}
>
- {form.identityFile.split(/[/\\]/).pop()}
+ {identityFileName}
</code>
<button
type="button"
onClick={() => setKeysOpenMode('pinPick')}
+ disabled={connectionFieldsReadOnly}
className="h-7 rounded-full px-3 text-12 border"
style={{
backgroundColor: 'transparent',
@@ -550,7 +677,13 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
</button>
<button
type="button"
- onClick={() => setForm({ ...form, identityFile: '' })}
+ onClick={() => setForm({
+ ...form,
+ identityFile: '',
+ identityFileUnchanged: false,
+ identityFileName: '',
+ })}
+ disabled={connectionFieldsReadOnly}
className="h-7 rounded-full px-3 text-12 border"
style={{
backgroundColor: 'transparent',
@@ -565,6 +698,7 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
<button
type="button"
onClick={() => setKeysOpenMode('pinPick')}
+ disabled={connectionFieldsReadOnly}
className="self-start inline-flex items-center gap-1 h-7 rounded-full px-3 text-12 leading-none border"
style={{
backgroundColor: 'transparent',
@@ -580,7 +714,7 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
className="text-11"
style={{ color: 'var(--settings-integration-subtitle)' }}
>
- {form.identityFile
+ {hasIdentityFile
? t('settings.remote.add.auth.pinnedKeyHintSet')
: t('settings.remote.add.auth.pinnedKeyHintUnset')}
</span>
@@ -605,6 +739,12 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
)}
</div>
+ {connectionFieldsReadOnly && (
+ <p className="text-12" style={{ color: 'var(--settings-integration-subtitle)' }}>
+ {t('settings.remote.edit.authenticationFromSshConfig')}
+ </p>
+ )}
+
{/* ── Agent Proxy ──
开关 + 双模式。pref 落 desktop 本地 ssh-host-prefs.json (不写
~/.ssh/config)。tunnel 模式: 远端 127.0.0.1:<固定端口> → 独立 SSH
@@ -765,8 +905,9 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
pick → key-file mode picking identityFile (authMethod stays 'key')
pinPick → agent mode pinning the agent to one key (authMethod stays 'agent')
manage → pure inspection, no mutation
- identityFile in both pick/pinPick is the private key path; resolveAuth
- derives the matching .pub for the FilteredAgent fingerprint lookup. */}
+ identityFile in both pick/pinPick is the newly selected private-key
+ path. Existing paths stay in Main and are represented here only by a
+ basename plus identityFileUnchanged. */}
<SshKeySetupDialog
hostId={null}
hostInline={{
@@ -778,7 +919,12 @@ function HostForm({ mode, initial, busy, onSubmit, onCancel }: HostFormProps) {
onOpenChange={(open) => { if (!open) setKeysOpenMode(null); }}
onKeyPicked={(keysOpenMode === 'pick' || keysOpenMode === 'pinPick')
? (_pubkeyPath, privateKeyPath) => {
- setForm((prev) => ({ ...prev, identityFile: privateKeyPath }));
+ setForm((prev) => ({
+ ...prev,
+ identityFile: privateKeyPath,
+ identityFileUnchanged: false,
+ identityFileName: privateKeyPath.split(/[/\\]/).pop() ?? '',
+ }));
setKeysOpenMode(null);
}
: undefined}
@@ -832,17 +978,23 @@ function RadioOption({
label,
hint,
onClick,
+ disabled = false,
}: {
checked: boolean;
label: string;
hint: string;
onClick: () => void;
+ disabled?: boolean;
}) {
return (
<button
type="button"
onClick={onClick}
- className="flex flex-1 flex-col gap-1 items-start text-left rounded-lg border p-3 transition-colors"
+ disabled={disabled}
+ className={cn(
+ 'flex flex-1 flex-col gap-1 items-start text-left rounded-lg border p-3 transition-colors',
+ disabled && 'cursor-not-allowed opacity-60',
+ )}
style={{
backgroundColor: checked
? 'var(--settings-menu-bg-selected)'
@@ -867,6 +1019,8 @@ function RadioOption({
export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}) {
const { t } = useTranslation();
const [hosts, setHosts] = useState<RemoteHostSnapshot[]>([]);
+ const [configWarningCount, setConfigWarningCount] = useState(0);
+ const [configDiagnostic, setConfigDiagnostic] = useState<SshConfigDiagnosticKind | null>(null);
const [adding, setAdding] = useState(false);
/** Per-host busy flag so per-row buttons disable independently of each other. */
const [busyIds, setBusyIds] = useState<ReadonlySet<string>>(() => new Set());
@@ -897,15 +1051,21 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
});
}, []);
+ const applyListResult = useCallback((res: RemoteSshListResult) => {
+ setHosts(res.hosts);
+ setConfigWarningCount(res.warningCount ?? 0);
+ setConfigDiagnostic(res.diagnostic?.kind ?? null);
+ remoteSshHostsStore.replace(res.hosts);
+ }, []);
+
const refresh = useCallback(async () => {
try {
const res = await window.electronAPI.remoteSsh.list();
- setHosts(res.hosts);
- remoteSshHostsStore.replace(res.hosts);
+ applyListResult(res);
} catch (err) {
toast.error(t(mapIpcErrorToI18nKey(err, { fallback: 'settings.remote.toast.loadFailed' })));
}
- }, [t]);
+ }, [applyListResult, t]);
useEffect(() => {
void refresh();
@@ -926,13 +1086,23 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
const handleReload = useCallback(async () => {
try {
const res = await window.electronAPI.remoteSsh.reloadConfig();
- setHosts(res.hosts as RemoteHostSnapshot[]);
- remoteSshHostsStore.replace(res.hosts);
- toast.success(t('settings.remote.toast.reloaded'));
+ applyListResult(res);
+ if (res.diagnostic) toast.error(t(`settings.remote.configDiagnostic.${res.diagnostic.kind}`));
+ else toast.success(t('settings.remote.toast.reloaded'));
} catch (err) {
toast.error(t(mapIpcErrorToI18nKey(err, { fallback: 'settings.remote.toast.loadFailed' })));
}
- }, [t]);
+ }, [applyListResult, t]);
+
+ const reloadCommittedMutationOnce = useCallback(async (): Promise<boolean> => {
+ try {
+ const res = await window.electronAPI.remoteSsh.reloadConfig();
+ applyListResult(res);
+ return !res.diagnostic;
+ } catch {
+ return false;
+ }
+ }, [applyListResult]);
const handleConnect = useCallback(async (id: string) => {
setBusy(id, true);
@@ -1000,14 +1170,20 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
setHosts((prev) => prev.filter((h) => h.config.id !== id));
remoteSshHostsStore.remove(id);
} catch (err) {
- toast.error(t(mapIpcErrorToI18nKey(err, { fallback: 'settings.remote.toast.removeFailed' })));
+ const recovered = extractIpcError(err)?.code === 'SSH_CONFIG_RELOAD_REQUIRED'
+ && await reloadCommittedMutationOnce();
+ if (!recovered) {
+ toast.error(t(mapIpcErrorToI18nKey(err, { fallback: 'settings.remote.toast.removeFailed' })));
+ }
} finally {
setBusy(id, false);
}
- }, [setBusy, t]);
+ }, [reloadCommittedMutationOnce, setBusy, t]);
const handleEdit = useCallback(async (form: AddFormState) => {
setEditBusy(true);
+ const currentHost = hosts.find((host) => host.config.id === form.id);
+ let connectionFieldsChanged = false;
try {
const port = parseInt(form.port, 10);
// identityFile is meaningful in BOTH auth modes:
@@ -1015,6 +1191,16 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
// agent → optional pin (FilteredAgent only offers this one key)
// Empty string from the input = unset, send undefined.
const trimmedIdentityFile = form.identityFile.trim();
+ const normalizedPort = Number.isFinite(port) && port > 0 ? port : 22;
+ const identityFileChanged = !form.identityFileUnchanged
+ && (currentHost?.config.identityFileConfigured === true || trimmedIdentityFile.length > 0);
+ connectionFieldsChanged = currentHost !== undefined && (
+ currentHost.config.hostname !== form.hostname.trim()
+ || currentHost.config.user !== form.user.trim()
+ || currentHost.config.port !== normalizedPort
+ || currentHost.config.authMethod !== form.authMethod
+ || identityFileChanged
+ );
const proxyPayload = buildAgentProxyPayload(form);
if (!proxyPayload.ok) {
toast.error(t(proxyPayload.errorKey));
@@ -1022,11 +1208,13 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
}
await window.electronAPI.remoteSsh.update({
id: form.id.trim(),
+ displayName: form.displayName.trim() || form.id.trim(),
hostname: form.hostname.trim(),
user: form.user.trim(),
- port: Number.isFinite(port) && port > 0 ? port : 22,
+ port: normalizedPort,
authMethod: form.authMethod,
identityFile: trimmedIdentityFile || undefined,
+ identityFileUnchanged: form.identityFileUnchanged,
agentProxy: proxyPayload.agentProxy,
});
// refresh() pulls the latest snapshot; updateConfig already fired a
@@ -1036,11 +1224,22 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
setEditingId(null);
toast.success(t('settings.remote.toast.edited'));
} catch (err) {
- toast.error(t(mapIpcErrorToI18nKey(err, { fallback: 'settings.remote.toast.editFailed' })));
+ const code = extractIpcError(err)?.code;
+ const prefsWriteFailed = code === 'SSH_HOST_PREFS_WRITE_FAILED';
+ const recovered = (code === 'SSH_CONFIG_RELOAD_REQUIRED'
+ || (prefsWriteFailed && connectionFieldsChanged))
+ && await reloadCommittedMutationOnce();
+ if (recovered) {
+ setEditingId(null);
+ if (prefsWriteFailed) toast.error(t('ipcError.SSH_HOST_PREFS_WRITE_FAILED'));
+ else toast.success(t('settings.remote.toast.edited'));
+ } else {
+ toast.error(t(mapIpcErrorToI18nKey(err, { fallback: 'settings.remote.toast.editFailed' })));
+ }
} finally {
setEditBusy(false);
}
- }, [refresh, t]);
+ }, [hosts, refresh, reloadCommittedMutationOnce, t]);
const handleAdd = useCallback(async (form: AddFormState) => {
setAddBusy(true);
@@ -1055,6 +1254,7 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
}
await window.electronAPI.remoteSsh.add({
id: form.id.trim(),
+ displayName: form.displayName.trim() || form.id.trim(),
hostname: form.hostname.trim(),
user: form.user.trim(),
port: Number.isFinite(port) && port > 0 ? port : 22,
@@ -1066,11 +1266,30 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
setAdding(false);
toast.success(t('settings.remote.toast.added'));
} catch (err) {
- toast.error(t(mapIpcErrorToI18nKey(err, { fallback: 'settings.remote.toast.addFailed' })));
+ const code = extractIpcError(err)?.code;
+ if (code === 'PRECONDITION_FAILED') {
+ // The main process rejected a concurrent SSH-config ownership change.
+ // Re-read the graph so the conflicting alias is visible before the
+ // user retries; this is not a committed mutation and must not close
+ // the add form or show a success toast.
+ await reloadCommittedMutationOnce();
+ toast.error(t('settings.remote.toast.addConflict'));
+ return;
+ }
+ const prefsWriteFailed = code === 'SSH_HOST_PREFS_WRITE_FAILED';
+ const recovered = (code === 'SSH_CONFIG_RELOAD_REQUIRED' || prefsWriteFailed)
+ && await reloadCommittedMutationOnce();
+ if (recovered) {
+ setAdding(false);
+ if (prefsWriteFailed) toast.error(t('ipcError.SSH_HOST_PREFS_WRITE_FAILED'));
+ else toast.success(t('settings.remote.toast.added'));
+ } else {
+ toast.error(t(mapIpcErrorToI18nKey(err, { fallback: 'settings.remote.toast.addFailed' })));
+ }
} finally {
setAddBusy(false);
}
- }, [refresh, t]);
+ }, [refresh, reloadCommittedMutationOnce, t]);
return (
<div className="flex flex-col gap-[14px]">
@@ -1128,6 +1347,21 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
</div>
</div>
+ {(configDiagnostic !== null || configWarningCount > 0) && (
+ <div className="flex items-start gap-2 rounded-lg bg-[var(--warning-bg-soft)] px-3 py-2.5">
+ <AlertTriangle
+ size={15}
+ aria-hidden="true"
+ className="mt-0.5 shrink-0 text-[var(--warning-fg)]"
+ />
+ <p className="text-12 leading-[1.5] text-[var(--settings-section-title)]">
+ {configDiagnostic
+ ? t(`settings.remote.configDiagnostic.${configDiagnostic}`)
+ : t('settings.remote.configWarning')}
+ </p>
+ </div>
+ )}
+
<div
className={cn('flex flex-col rounded-xl', 'bg-[var(--settings-theme-card-bg)]')}
style={{ border: '1px solid var(--settings-theme-card-border)' }}
@@ -1180,11 +1414,14 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
busy={editBusy}
initial={{
id: snap.config.id,
+ displayName: snap.config.displayName ?? snap.config.id,
hostname: snap.config.hostname,
user: snap.config.user,
port: String(snap.config.port ?? 22),
authMethod: snap.config.authMethod === 'key' ? 'key' : 'agent',
- identityFile: snap.config.identityFile ?? '',
+ identityFile: '',
+ identityFileUnchanged: snap.config.identityFileConfigured,
+ identityFileName: snap.config.identityFileName ?? '',
agentProxyEnabled: snap.agentProxy?.enabled === true,
agentProxyMode: snap.agentProxy?.mode === 'env' ? 'env' : 'tunnel',
agentProxyAddr: snap.agentProxy?.mode === 'tunnel'
@@ -1197,6 +1434,7 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}
? snap.agentProxy.proxyUrl
: 'http://127.0.0.1:7890',
}}
+ connectionFieldsReadOnly={!snap.config.managedByCindy}
onSubmit={handleEdit}
onCancel={() => setEditingId(null)}
/>
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/RemoteSection.addFormOrder.test.ts b/apps/desktop/src/renderer/components/settings/__tests__/RemoteSection.addFormOrder.test.ts
index cab73e69ef..f6d3b7c403 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/RemoteSection.addFormOrder.test.ts
+++ b/apps/desktop/src/renderer/components/settings/__tests__/RemoteSection.addFormOrder.test.ts
@@ -19,4 +19,42 @@ describe('RemoteSection add form order', () => {
expect(hostList).toBeGreaterThan(addForm);
expect(source).toContain('idx > 0 || adding');
});
+
+ it('keeps external connection fields read-only while showing display name and alias', () => {
+ expect(source).toContain('snap.config.displayName?.trim() || snap.config.id');
+ expect(source).toContain('displayName !== snap.config.id');
+ expect(source).toContain('!snap.config.managedByCindy');
+ expect(source).toContain('connectionFieldsReadOnly={!snap.config.managedByCindy}');
+ expect(source).toContain("t('settings.remote.edit.authenticationFromSshConfig')");
+ expect(source).toContain('{snap.config.managedByCindy && (');
+ });
+
+ it('rejects character-class aliases that discovery intentionally excludes', () => {
+ expect(source).toContain("/\\s|[*?!\\[]/.test(form.id)");
+ });
+
+ it('surfaces non-fatal SSH config discovery warnings', () => {
+ expect(source).toContain('setConfigWarningCount(res.warningCount ?? 0)');
+ expect(source).toContain("t('settings.remote.configWarning')");
+ });
+
+ it('surfaces fatal diagnostics and retries committed mutations only once', () => {
+ expect(source).toContain('setConfigDiagnostic(res.diagnostic?.kind ?? null)');
+ expect(source).toContain('settings.remote.configDiagnostic.${configDiagnostic}');
+ expect(source).toContain('const reloadCommittedMutationOnce = useCallback');
+ expect(source.match(/await reloadCommittedMutationOnce\(\)/g)).toHaveLength(4);
+ expect(source).toContain("code === 'PRECONDITION_FAILED'");
+ expect(source).toContain("t('settings.remote.toast.addConflict')");
+ expect(source).toContain("code === 'SSH_HOST_PREFS_WRITE_FAILED'");
+ expect(source).toContain('(prefsWriteFailed && connectionFieldsChanged)');
+ expect(source).toContain("t('ipcError.SSH_HOST_PREFS_WRITE_FAILED')");
+ expect(source).not.toContain('while (extractIpcError');
+ });
+
+ it('preserves configured identities without receiving their absolute paths', () => {
+ expect(source).toContain('identityFileUnchanged: snap.config.identityFileConfigured');
+ expect(source).toContain('identityFileName: snap.config.identityFileName ??');
+ expect(source).toContain('identityFileUnchanged: form.identityFileUnchanged');
+ expect(source).not.toContain('snap.config.identityFile ??');
+ });
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/remoteProjectIdentity.ts b/apps/desktop/src/renderer/features/cc-agent/lib/remoteProjectIdentity.ts
index 6a06585c8f..3809638381 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/remoteProjectIdentity.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/remoteProjectIdentity.ts
@@ -102,11 +102,15 @@ export function resolveRemoteProjectMachineIdentity(
const endpoint = `${host.config.user}@${host.config.hostname}${
host.config.port === 22 ? '' : `:${host.config.port}`
}`;
+ const displayName = host.config.displayName?.trim() || host.config.id;
+ const label = displayName === host.config.id
+ ? host.config.id
+ : `${displayName} (${host.config.id})`;
return {
kind: 'ssh',
- label: host.config.id,
+ label,
detail: endpoint,
- displayLabel: joinIdentity(host.config.id, endpoint),
+ displayLabel: joinIdentity(label, endpoint),
};
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index cef79b9651..ba6150a03c 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -16,6 +16,12 @@
"REMOTE_NATIVE_OAUTH_UNAVAILABLE": "Claude.ai subscription is not connected — connect it first or pick a gateway model",
"DEVICE_LINK_DEVICE_UNRESPONSIVE": "The target device is not responding. Check the remote device and try again.",
"INTERNAL": "Operation failed. Please try again later.",
+ "SSH_CONFIG_CONCURRENT_MODIFICATION": "The SSH configuration changed on disk. Reload it and try again.",
+ "SSH_CONFIG_RELOAD_REQUIRED": "The SSH config was saved, but Cindy could not refresh it. Reload the SSH configuration.",
+ "SSH_CONFIG_OWNERSHIP_REQUIRED": "Cindy cannot safely manage this SSH configuration. Reload it, then verify the Cindy ownership marker and that the host alias is unique.",
+ "SSH_CONFIG_AUTH_UNSUPPORTED": "Cindy cannot safely reproduce some SSH configuration rules for this host. Terminal SSH may still work; review Match, conditional Include, IdentityAgent, IdentitiesOnly, and public-key settings.",
+ "SSH_AGENT_UNAVAILABLE": "The SSH Agent is unavailable. Start it, load the matching private key with ssh-add, and try again.",
+ "SSH_HOST_PREFS_WRITE_FAILED": "The host is still saved, but its display name or Agent Proxy settings could not be saved. Check local storage permissions and try again.",
"RIGHT_SIDEBAR_TOO_MANY_TABS": "This task has reached its tab limit. Close some tabs first",
"RIGHT_SIDEBAR_STATE_TOO_LARGE": "Tab content is too large to add",
"RIGHT_SIDEBAR_UNKNOWN_KIND": "This tab type is unavailable"
@@ -168,6 +174,13 @@
"title": "Remote machines",
"footnote": "Phase A: SSH connection management only. Running agents on the remote arrives in a later update.",
"viaAuth": "via {{label}}",
+ "readOnlyFromSshConfig": "Connection details come from SSH configuration",
+ "configWarning": "Cindy cannot evaluate some SSH configuration rules. The host list or connection details may differ from terminal SSH.",
+ "configDiagnostic": {
+ "io": "Cindy could not read your SSH configuration. The last successfully loaded hosts are still shown. Check file permissions and reload.",
+ "syntax": "Cindy could not parse your SSH configuration. The last successfully loaded hosts are still shown. Fix the configuration and reload.",
+ "limit": "The SSH configuration is too deeply nested or too large for Cindy to read safely. The last successfully loaded hosts are still shown."
+ },
"empty": {
"title": "No remote machines yet.",
"hint": "Click \"Add\" to register one, or click the refresh icon to import from ~/.ssh/config."
@@ -199,7 +212,9 @@
},
"edit": {
"title": "Edit {{id}}",
- "submit": "Save changes"
+ "submit": "Save changes",
+ "connectionFieldsReadOnly": "Connection details from SSH configuration are read-only here. Display name, auto-connect, and Agent Proxy remain editable.",
+ "authenticationFromSshConfig": "Authentication comes from SSH configuration."
},
"keys": {
"title": "Set up SSH key",
@@ -276,6 +291,8 @@
"add": {
"title": "Add a remote machine",
"alias": "Alias",
+ "displayName": "Display name",
+ "displayNamePlaceholder": "Optional name shown in Cindy",
"hostname": "Hostname",
"user": "User",
"port": "Port",
@@ -376,6 +393,7 @@
"reloaded": "Reloaded ~/.ssh/config",
"loadFailed": "Failed to load remote machines",
"addFailed": "Failed to add machine",
+ "addConflict": "The SSH configuration changed while adding this machine. Reload it, review the host entry, and try again.",
"connectFailed": "Connection failed",
"disconnectFailed": "Disconnect failed",
"removeFailed": "Remove failed",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3d14ca1fac..63e23719ed 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -16,6 +16,12 @@
"REMOTE_NATIVE_OAUTH_UNAVAILABLE": "Claude.ai サブスクリプションが未接続です。先に接続するか、ゲートウェイモデルを選択してください",
"DEVICE_LINK_DEVICE_UNRESPONSIVE": "対象デバイスが応答していません。リモートデバイスを確認して再試行してください。",
"INTERNAL": "操作に失敗しました。しばらくしてから再試行してください。",
+ "SSH_CONFIG_CONCURRENT_MODIFICATION": "SSH 設定がディスク上で変更されました。再読み込みしてからもう一度お試しください。",
+ "SSH_CONFIG_RELOAD_REQUIRED": "SSH 設定は保存されましたが、Cindy で再読み込みできませんでした。SSH 設定を再読み込みしてください。",
+ "SSH_CONFIG_OWNERSHIP_REQUIRED": "Cindy はこの SSH 設定を安全に管理できません。再読み込みして、Cindy の所有マーカーとホストエイリアスの一意性を確認してください。",
+ "SSH_CONFIG_AUTH_UNSUPPORTED": "Cindy はこのホストの一部の SSH 設定規則を安全に再現できません。ターミナルの SSH は動作する場合があります。Match、条件付き Include、IdentityAgent、IdentitiesOnly、公開鍵設定を確認してください。",
+ "SSH_AGENT_UNAVAILABLE": "SSH Agent を使用できません。SSH Agent を起動し、ssh-add で対応する秘密鍵を読み込んでから再試行してください。",
+ "SSH_HOST_PREFS_WRITE_FAILED": "ホストは保存されていますが、表示名または Agent Proxy の設定を保存できませんでした。ローカルストレージの権限を確認して再試行してください。",
"RIGHT_SIDEBAR_TOO_MANY_TABS": "このタスクのタブ数の上限に達しました。いくつかのタブを閉じてください",
"RIGHT_SIDEBAR_STATE_TOO_LARGE": "タブの内容が大きすぎるため、追加できません",
"RIGHT_SIDEBAR_UNKNOWN_KIND": "このタブの種類は現在使用できません"
@@ -168,6 +174,13 @@
"title": "リモートマシン",
"footnote": "Phase A は SSH 接続管理のみ。リモートでのエージェント実行は今後のアップデートで対応します。",
"viaAuth": "{{label}} で認証",
+ "readOnlyFromSshConfig": "接続情報は SSH 設定から読み込まれています",
+ "configWarning": "一部の SSH 設定ルールを Cindy では評価できません。ホスト一覧や接続情報がターミナルの SSH と異なる場合があります。",
+ "configDiagnostic": {
+ "io": "Cindy は SSH 設定を読み込めませんでした。最後に正常に読み込んだホストを引き続き表示しています。ファイルのアクセス権を確認して、再読み込みしてください。",
+ "syntax": "Cindy は SSH 設定を解析できませんでした。最後に正常に読み込んだホストを引き続き表示しています。設定を修正して、再読み込みしてください。",
+ "limit": "SSH 設定のネストが深すぎるか、サイズが大きすぎるため、Cindy で安全に読み込めません。最後に正常に読み込んだホストを引き続き表示しています。"
+ },
"empty": {
"title": "リモートマシンはまだありません。",
"hint": "「追加」で登録するか、更新アイコンで ~/.ssh/config から取り込めます。"
@@ -199,7 +212,9 @@
},
"edit": {
"title": "{{id}} を編集",
- "submit": "変更を保存"
+ "submit": "変更を保存",
+ "connectionFieldsReadOnly": "SSH 設定から読み込まれた接続情報はここでは読み取り専用です。表示名、自動接続、Agent Proxy は変更できます。",
+ "authenticationFromSshConfig": "認証情報は SSH 設定から読み込まれます。"
},
"keys": {
"title": "SSH 鍵を設定",
@@ -276,6 +291,8 @@
"add": {
"title": "リモートマシンを追加",
"alias": "エイリアス",
+ "displayName": "表示名",
+ "displayNamePlaceholder": "任意。Cindy 内でのみ表示",
"hostname": "ホスト名",
"user": "ユーザー",
"port": "ポート",
@@ -376,6 +393,7 @@
"reloaded": "~/.ssh/config を再読み込みしました",
"loadFailed": "リモートマシンの読み込みに失敗",
"addFailed": "マシンの追加に失敗",
+ "addConflict": "マシンの追加中に SSH 設定が変更されました。設定を再読み込みし、ホスト項目を確認してから再試行してください。",
"connectFailed": "接続に失敗",
"disconnectFailed": "切断に失敗",
"removeFailed": "削除に失敗",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index cf47325d25..c991a2241c 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -16,6 +16,12 @@
"REMOTE_NATIVE_OAUTH_UNAVAILABLE": "Claude.ai 구독이 연결되지 않았습니다. 먼저 연결하거나 게이트웨이 모델을 선택하세요",
"DEVICE_LINK_DEVICE_UNRESPONSIVE": "대상 장치가 응답하지 않습니다. 원격 장치를 확인한 후 다시 시도하세요.",
"INTERNAL": "작업에 실패했습니다. 잠시 후 다시 시도하세요.",
+ "SSH_CONFIG_CONCURRENT_MODIFICATION": "디스크의 SSH 구성이 변경되었습니다. 다시 불러온 후 재시도하세요.",
+ "SSH_CONFIG_RELOAD_REQUIRED": "SSH 설정은 저장되었지만 Cindy에서 새로 고치지 못했습니다. SSH 설정을 다시 불러오세요.",
+ "SSH_CONFIG_OWNERSHIP_REQUIRED": "Cindy가 이 SSH 구성을 안전하게 관리할 수 없습니다. 다시 불러온 후 Cindy 소유권 표시와 호스트 별칭의 고유성을 확인하세요.",
+ "SSH_CONFIG_AUTH_UNSUPPORTED": "Cindy가 이 호스트의 일부 SSH 설정 규칙을 안전하게 재현할 수 없습니다. 터미널 SSH는 계속 작동할 수 있으니 Match, 조건부 Include, IdentityAgent, IdentitiesOnly 및 공개 키 설정을 확인하세요.",
+ "SSH_AGENT_UNAVAILABLE": "SSH Agent를 사용할 수 없습니다. SSH Agent를 시작하고 ssh-add로 해당 개인 키를 불러온 뒤 다시 시도하세요.",
+ "SSH_HOST_PREFS_WRITE_FAILED": "호스트는 저장되었지만 표시 이름 또는 Agent Proxy 설정을 저장하지 못했습니다. 로컬 저장소 권한을 확인한 후 다시 시도하세요.",
"RIGHT_SIDEBAR_TOO_MANY_TABS": "이 작업의 탭 한도에 도달했습니다. 일부 탭을 닫아 주세요",
"RIGHT_SIDEBAR_STATE_TOO_LARGE": "탭 내용이 너무 커서 추가할 수 없습니다",
"RIGHT_SIDEBAR_UNKNOWN_KIND": "이 탭 유형은 현재 사용할 수 없습니다"
@@ -168,6 +174,13 @@
"title": "원격 머신",
"footnote": "Phase A 는 SSH 연결 관리만 지원합니다. 원격에서 에이전트 실행은 다음 업데이트에서 제공됩니다.",
"viaAuth": "{{label}} 로 인증",
+ "readOnlyFromSshConfig": "연결 정보는 SSH 설정에서 가져옵니다",
+ "configWarning": "Cindy에서 일부 SSH 설정 규칙을 해석할 수 없습니다. 호스트 목록이나 연결 정보가 터미널 SSH와 다를 수 있습니다.",
+ "configDiagnostic": {
+ "io": "Cindy에서 SSH 설정을 읽을 수 없습니다. 마지막으로 정상적으로 불러온 호스트를 계속 표시합니다. 파일 권한을 확인한 후 다시 불러오세요.",
+ "syntax": "Cindy에서 SSH 설정을 해석할 수 없습니다. 마지막으로 정상적으로 불러온 호스트를 계속 표시합니다. 설정을 수정한 후 다시 불러오세요.",
+ "limit": "SSH 설정이 너무 깊게 중첩되어 있거나 너무 커서 Cindy에서 안전하게 읽을 수 없습니다. 마지막으로 정상적으로 불러온 호스트를 계속 표시합니다."
+ },
"empty": {
"title": "아직 원격 머신이 없습니다.",
"hint": "\"추가\"를 클릭해 등록하거나, 새로 고침 아이콘으로 ~/.ssh/config 에서 가져오세요."
@@ -199,7 +212,9 @@
},
"edit": {
"title": "{{id}} 편집",
- "submit": "변경 저장"
+ "submit": "변경 저장",
+ "connectionFieldsReadOnly": "SSH 설정에서 가져온 연결 정보는 여기서 읽기 전용입니다. 표시 이름, 자동 연결, Agent Proxy는 수정할 수 있습니다.",
+ "authenticationFromSshConfig": "인증 정보는 SSH 설정에서 가져옵니다."
},
"keys": {
"title": "SSH 키 설정",
@@ -276,6 +291,8 @@
"add": {
"title": "원격 머신 추가",
"alias": "별칭",
+ "displayName": "표시 이름",
+ "displayNamePlaceholder": "선택 사항, Cindy에서만 표시",
"hostname": "호스트명",
"user": "사용자",
"port": "포트",
@@ -376,6 +393,7 @@
"reloaded": "~/.ssh/config 를 다시 읽었습니다",
"loadFailed": "원격 머신 로드 실패",
"addFailed": "머신 추가 실패",
+ "addConflict": "머신을 추가하는 동안 SSH 설정이 변경되었습니다. 설정을 다시 불러온 뒤 호스트 항목을 확인하고 다시 시도하세요.",
"connectFailed": "연결 실패",
"disconnectFailed": "끊기 실패",
"removeFailed": "제거 실패",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 3e902efc51..cf7e8cc6c4 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -12,6 +12,12 @@
"REMOTE_NATIVE_OAUTH_UNAVAILABLE": "未连接 Claude.ai 订阅,请先连接或选择网关模型",
"DEVICE_LINK_DEVICE_UNRESPONSIVE": "目标设备长时间无响应,请检查远程设备后重试",
"INTERNAL": "操作失败,请稍后重试。",
+ "SSH_CONFIG_CONCURRENT_MODIFICATION": "SSH 配置已在磁盘上发生变化,请重新加载后再试。",
+ "SSH_CONFIG_RELOAD_REQUIRED": "SSH 配置已保存,但 Cindy 刷新失败。请重新加载 SSH 配置。",
+ "SSH_CONFIG_OWNERSHIP_REQUIRED": "Cindy 无法安全管理此 SSH 配置。请重新加载,并确认 Cindy 所有权标记存在且主机别名唯一。",
+ "SSH_CONFIG_AUTH_UNSUPPORTED": "Cindy 无法安全复现此主机的部分 SSH 配置规则。终端 SSH 仍可能成功;请检查 Match、条件 Include、IdentityAgent、IdentitiesOnly 和公钥设置。",
+ "SSH_AGENT_UNAVAILABLE": "SSH Agent 当前不可用。请启动 SSH Agent,并用 ssh-add 加载对应私钥后重试。",
+ "SSH_HOST_PREFS_WRITE_FAILED": "主机仍已保存,但显示名称或 Agent Proxy 设置未能保存。请检查本地存储权限后重试。",
"REMOTE_WORKDIR_INVALID": "远程项目目录无效,请重新选择项目目录。",
"REMOTE_WORKDIR_NOT_FOUND": "远程项目目录不存在,请重新选择项目目录。",
"REMOTE_WORKDIR_NOT_DIRECTORY": "远程项目路径不是文件夹,请重新选择项目目录。",
@@ -168,6 +174,13 @@
"title": "远端机器",
"footnote": "第一版仅支持 SSH 连接管理。在远端运行 Agent 的能力将在后续版本中加入。",
"viaAuth": "通过 {{label}} 认证",
+ "readOnlyFromSshConfig": "连接信息来自 SSH 配置",
+ "configWarning": "部分 SSH 配置规则 Cindy 无法解析,主机列表或连接信息可能与终端 SSH 不一致。",
+ "configDiagnostic": {
+ "io": "Cindy 无法读取 SSH 配置。这里仍显示上次成功读取的主机;请检查文件权限,然后重新加载。",
+ "syntax": "Cindy 无法解析 SSH 配置。这里仍显示上次成功读取的主机;请修复配置,然后重新加载。",
+ "limit": "SSH 配置的嵌套过深或内容过大,Cindy 无法安全读取。这里仍显示上次成功读取的主机。"
+ },
"empty": {
"title": "还没有远端机器。",
"hint": "点击\"添加\"注册一台,或点刷新图标从 ~/.ssh/config 导入。"
@@ -199,7 +212,9 @@
},
"edit": {
"title": "编辑 {{id}}",
- "submit": "保存修改"
+ "submit": "保存修改",
+ "connectionFieldsReadOnly": "来自 SSH 配置的连接信息在这里为只读;显示名、自动连接和 Agent Proxy 仍可修改。",
+ "authenticationFromSshConfig": "认证信息来自 SSH 配置。"
},
"keys": {
"title": "配置 SSH 密钥",
@@ -276,6 +291,8 @@
"add": {
"title": "添加一台远端机器",
"alias": "别名",
+ "displayName": "显示名",
+ "displayNamePlaceholder": "可选,仅在 Cindy 中显示",
"hostname": "主机名",
"user": "用户",
"port": "端口",
@@ -376,6 +393,7 @@
"reloaded": "已重新读取 ~/.ssh/config",
"loadFailed": "加载远端机器失败",
"addFailed": "添加机器失败",
+ "addConflict": "添加期间 SSH 配置发生了变化。请重新加载配置,检查该主机条目后再试。",
"connectFailed": "连接失败",
"disconnectFailed": "断开失败",
"removeFailed": "移除失败",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 37e3eb4860..5eff0cc345 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -12,6 +12,12 @@
"REMOTE_NATIVE_OAUTH_UNAVAILABLE": "未連線 Claude.ai 訂閱,請先連線或選擇閘道器模型",
"DEVICE_LINK_DEVICE_UNRESPONSIVE": "目標裝置長時間無響應,請檢查遠端裝置後重試",
"INTERNAL": "操作失敗,請稍後重試。",
+ "SSH_CONFIG_CONCURRENT_MODIFICATION": "SSH 設定已在磁碟上變更,請重新載入後再試。",
+ "SSH_CONFIG_RELOAD_REQUIRED": "SSH 設定已儲存,但 Cindy 重新整理失敗。請重新載入 SSH 設定。",
+ "SSH_CONFIG_OWNERSHIP_REQUIRED": "Cindy 無法安全管理此 SSH 設定。請重新載入,並確認 Cindy 所有權標記存在且主機別名唯一。",
+ "SSH_CONFIG_AUTH_UNSUPPORTED": "Cindy 無法安全重現此主機的部分 SSH 設定規則。終端 SSH 仍可能成功;請檢查 Match、條件式 Include、IdentityAgent、IdentitiesOnly 與公開金鑰設定。",
+ "SSH_AGENT_UNAVAILABLE": "SSH Agent 目前無法使用。請啟動 SSH Agent,並用 ssh-add 載入對應私密金鑰後再試。",
+ "SSH_HOST_PREFS_WRITE_FAILED": "主機仍已儲存,但顯示名稱或 Agent Proxy 設定未能儲存。請檢查本機儲存權限後再試。",
"REMOTE_WORKDIR_INVALID": "遠端專案目錄無效,請重新選擇專案目錄。",
"REMOTE_WORKDIR_NOT_FOUND": "遠端專案目錄不存在,請重新選擇專案目錄。",
"REMOTE_WORKDIR_NOT_DIRECTORY": "遠端專案路徑不是資料夾,請重新選擇專案目錄。",
@@ -168,6 +174,13 @@
"title": "遠端機器",
"footnote": "第一版僅支援 SSH 連線管理。在遠端執行 Agent 的能力將在後續版本中加入。",
"viaAuth": "透過 {{label}} 認證",
+ "readOnlyFromSshConfig": "連線資訊來自 SSH 設定",
+ "configWarning": "部分 SSH 設定規則 Cindy 無法解析,主機列表或連線資訊可能與終端 SSH 不一致。",
+ "configDiagnostic": {
+ "io": "Cindy 無法讀取 SSH 設定。這裡仍顯示上次成功讀取的主機;請檢查檔案權限,然後重新載入。",
+ "syntax": "Cindy 無法解析 SSH 設定。這裡仍顯示上次成功讀取的主機;請修正設定,然後重新載入。",
+ "limit": "SSH 設定的巢狀層級過深或內容過大,Cindy 無法安全讀取。這裡仍顯示上次成功讀取的主機。"
+ },
"empty": {
"title": "還沒有遠端機器。",
"hint": "點選\"新增\"註冊一臺,或點重新整理圖示從 ~/.ssh/config 匯入。"
@@ -199,7 +212,9 @@
},
"edit": {
"title": "編輯 {{id}}",
- "submit": "儲存修改"
+ "submit": "儲存修改",
+ "connectionFieldsReadOnly": "來自 SSH 設定的連線資訊在此為唯讀;顯示名稱、自動連線和 Agent Proxy 仍可修改。",
+ "authenticationFromSshConfig": "驗證資訊來自 SSH 設定。"
},
"keys": {
"title": "配置 SSH 金鑰",
@@ -276,6 +291,8 @@
"add": {
"title": "新增一臺遠端機器",
"alias": "別名",
+ "displayName": "顯示名稱",
+ "displayNamePlaceholder": "選填,僅在 Cindy 中顯示",
"hostname": "主機名",
"user": "使用者",
"port": "埠",
@@ -376,6 +393,7 @@
"reloaded": "已重新讀取 ~/.ssh/config",
"loadFailed": "載入遠端機器失敗",
"addFailed": "新增機器失敗",
+ "addConflict": "新增期間 SSH 設定發生變化。請重新載入設定、檢查該主機項目後再試。",
"connectFailed": "連線失敗",
"disconnectFailed": "斷開失敗",
"removeFailed": "移除失敗",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 2590a6f866..c96c859dd5 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -102,10 +102,26 @@ interface EnvCheckResult {
// Voice-input wire types: re-export from voice-input-core to keep the IPC
// surface and the core package's contract in sync. `VoiceInputShortcut` is
// renderer-only (defined in voice-input/shortcut.ts) so it stays inline.
-// HostSnapshot 来自 transport-only package; desktop main 端 wrap 时附加
-// autoConnect / agentProxy 偏好字段 (本地 prefs, 不写入 ~/.ssh/config), 渲染层统一用
-// 这个扩展类型即可一次拿到完整信息, 不必再为单个字段单独 IPC。
-type RemoteHostSnapshot = import('@cindy/maker-remote-ssh').HostSnapshot & {
+// Renderer 只声明 Main 明确投影的 SSH 视图字段。transport package 内的
+// IdentityAgent、IdentityFile 累积列表和指纹属于 main-only 认证元数据,不能因
+// HostSnapshot 结构扩展而自动穿过 preload。Desktop 偏好字段在同一 payload 附加。
+type RemoteHostSnapshot = {
+ config: {
+ id: string;
+ displayName?: string;
+ hostname: string;
+ port: number;
+ user: string;
+ authMethod: 'agent' | 'key';
+ identityFileConfigured: boolean;
+ identityFileName?: string;
+ source: 'ssh-config' | 'manual';
+ managedByCindy: boolean;
+ };
+ status: import('@cindy/maker-remote-ssh').RemoteStatus;
+ lastError?: string;
+ lastAuthLabel?: string;
+ statusChangedAt: number;
autoConnect: boolean;
/** Agent 流量经 SSH 隧道走本地 Proxy 的 per-host 配置; 未开启 → null。 */
agentProxy: AgentProxyPrefPayload | null;
@@ -3767,12 +3783,21 @@ interface ElectronAPI {
};
// ── Remote SSH (Phase A) ───────────────────────────────────────────────
- // 连接管理 + ~/.ssh/config IO. host.config.id == ssh alias.
+ // 连接管理 + OpenSSH config 发现. host.config.id == ssh alias.
remoteSsh: {
- list: () => Promise<{ hosts: RemoteHostSnapshot[] }>;
- reloadConfig: () => Promise<{ hosts: RemoteHostSnapshot[] }>;
+ list: () => Promise<{
+ hosts: RemoteHostSnapshot[];
+ warningCount?: number;
+ diagnostic?: { kind: 'io' | 'syntax' | 'limit' } | null;
+ }>;
+ reloadConfig: () => Promise<{
+ hosts: RemoteHostSnapshot[];
+ warningCount?: number;
+ diagnostic?: { kind: 'io' | 'syntax' | 'limit' } | null;
+ }>;
add: (host: {
id: string;
+ displayName?: string;
hostname: string;
port?: number;
user: string;
@@ -3783,11 +3808,14 @@ interface ElectronAPI {
}) => Promise<{ host: RemoteHostSnapshot }>;
update: (host: {
id: string;
+ displayName?: string;
hostname: string;
port?: number;
user: string;
authMethod?: 'agent' | 'key';
identityFile?: string;
+ /** Preserve the existing main-only path without returning it to Renderer. */
+ identityFileUnchanged?: boolean;
agentProxy?: AgentProxyPrefPayload | null;
}) => Promise<{ host: RemoteHostSnapshot }>;
remove: (id: string) => Promise<{ ok: true }>;
diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.ts
index 1449e9b4f8..43b252f17e 100644
--- a/apps/desktop/src/shared/ipc-errors.ts
+++ b/apps/desktop/src/shared/ipc-errors.ts
@@ -86,6 +86,12 @@ export type IpcErrorCode =
| 'SSH_CONNECT_FAILED'
| 'SSH_AUTH_FAILED'
| 'SSH_CONFIG_IO_FAILED'
+ | 'SSH_CONFIG_CONCURRENT_MODIFICATION'
+ | 'SSH_CONFIG_OWNERSHIP_REQUIRED'
+ | 'SSH_CONFIG_RELOAD_REQUIRED'
+ | 'SSH_CONFIG_AUTH_UNSUPPORTED'
+ | 'SSH_AGENT_UNAVAILABLE'
+ | 'SSH_HOST_PREFS_WRITE_FAILED'
| 'SSH_HOST_NOT_FOUND'
// remote-ssh:配置的私钥文件在磁盘上不存在/不可读。与 SSH_CONNECT_FAILED 分开——
// 这是本机路径问题(缺失 / ~ 未展开 / 路径被改写),不是网络或服务器错误,renderer
@@ -315,6 +321,12 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>([
'SSH_CONNECT_FAILED',
'SSH_AUTH_FAILED',
'SSH_CONFIG_IO_FAILED',
+ 'SSH_CONFIG_CONCURRENT_MODIFICATION',
+ 'SSH_CONFIG_OWNERSHIP_REQUIRED',
+ 'SSH_CONFIG_RELOAD_REQUIRED',
+ 'SSH_CONFIG_AUTH_UNSUPPORTED',
+ 'SSH_AGENT_UNAVAILABLE',
+ 'SSH_HOST_PREFS_WRITE_FAILED',
'SSH_HOST_NOT_FOUND',
'SSH_KEY_FILE_NOT_FOUND',
'SSH_NOT_CONNECTED',
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index e3d31d1a49..386c339cc2 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -37,7 +37,7 @@
| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 4 | 4 | 2 |
| `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 |
| `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 49 | 0 | 81 |
-| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 142 | 102 | 703 |
+| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 142 | 103 | 707 |
| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/globals.css | 144 | 72 | 282 |
| `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及详情 `/skillhub/local/:kind/global/:name`、`/skillhub/local/:kind/project/:projectHash/:name` | InstallTargetPicker, PluginManagementLayout, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubMarketPreviewPanel | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx | 41 | 0 | 70 |
| `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketListView, SkillhubMarketPreviewPanel, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 41 | 0 | 50 |
diff --git a/packages/lizi-mcps/src/__tests__/cindy_sshMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/cindy_sshMcpServer.test.ts
index ddc676ca82..c811657527 100644
--- a/packages/lizi-mcps/src/__tests__/cindy_sshMcpServer.test.ts
+++ b/packages/lizi-mcps/src/__tests__/cindy_sshMcpServer.test.ts
@@ -28,6 +28,9 @@ function snapshot(partial: {
hostname?: string;
status?: SshHostSnapshotLike['status'];
lastError?: string;
+ identityFile?: string;
+ identityAgent?: string;
+ configuredIdentityFiles?: string[];
}): SshHostSnapshotLike {
return {
config: {
@@ -36,6 +39,17 @@ function snapshot(partial: {
port: 22,
user: 'deploy',
authMethod: 'agent',
+ ...(partial.identityFile ? { identityFile: partial.identityFile } : {}),
+ ...(partial.identityAgent || partial.configuredIdentityFiles
+ ? {
+ sshAuthentication: {
+ ...(partial.identityAgent ? { identityAgent: partial.identityAgent } : {}),
+ ...(partial.configuredIdentityFiles
+ ? { configuredIdentityFiles: partial.configuredIdentityFiles }
+ : {}),
+ },
+ }
+ : {}),
source: 'manual',
},
status: partial.status ?? 'ready',
@@ -84,6 +98,23 @@ function makeDeps(
const ensureReadyCalls: string[] = [];
const deps: SshMcpDeps = {
getPool: async () => pool,
+ redactSensitiveText: (snapshot, text) => {
+ const candidates = new Map<string, '<identity-agent>' | '<identity-file>'>();
+ for (const value of [
+ snapshot.config.identityFile,
+ ...(snapshot.config.sshAuthentication?.configuredIdentityFiles ?? []),
+ ]) {
+ if (value) candidates.set(value, '<identity-file>');
+ }
+ const identityAgent = snapshot.config.sshAuthentication?.identityAgent;
+ if (identityAgent) candidates.set(identityAgent, '<identity-agent>');
+ return Array.from(candidates, ([value, replacement]) => ({ value, replacement }))
+ .sort((left, right) => right.value.length - left.value.length)
+ .reduce(
+ (redacted, { value, replacement }) => redacted.split(value).join(replacement),
+ text,
+ );
+ },
ensureReady: async (id) => {
ensureReadyCalls.push(id);
},
@@ -141,6 +172,30 @@ describe('ssh_list_hosts', () => {
expect(hosts[1]).toMatchObject({ id: 'db-1', status: 'failed', lastError: 'boom' });
});
+ it('redacts local credential paths from model-visible host errors', async () => {
+ const identityFile = '/Users/alice/.ssh/client-prod';
+ const identityAgent = String.raw`C:\Users\alice\.ssh\agent.sock`;
+ const { pool } = makeFakePool([
+ snapshot({
+ id: 'private-paths',
+ status: 'failed',
+ identityFile,
+ identityAgent,
+ configuredIdentityFiles: [identityFile],
+ lastError: `IdentityFile ${identityFile} failed via ${identityAgent}`,
+ }),
+ ]);
+ const { deps } = makeDeps(pool);
+ const { payload } = await callParsed(makeRegistry(deps), 'ssh_list_hosts', {});
+
+ const [listed] = payload.hosts as Array<Record<string, unknown>>;
+ expect(listed.lastError).toBe(
+ 'IdentityFile <identity-file> failed via <identity-agent>',
+ );
+ expect(JSON.stringify(payload)).not.toContain('alice');
+ expect(JSON.stringify(payload)).not.toContain('client-prod');
+ });
+
it('empty pool returns ok with guidance hint', async () => {
const { pool } = makeFakePool([]);
const { deps } = makeDeps(pool);
@@ -352,6 +407,100 @@ describe('ssh_exec', () => {
expect(payload.errorCode).toBe('SSH_CONNECT_FAILED');
});
+ it.each([
+ ['SSH_CONFIG_AUTH_UNSUPPORTED', 'IdentityAgent none'],
+ ['SSH_AGENT_UNAVAILABLE', '$SSH_AUTH_SOCK is not set'],
+ ])('ensureReady %s remains a deterministic actionable error', async (code, detail) => {
+ const { pool } = makeFakePool([snapshot({ id: 'web-1' })]);
+ const { deps } = makeDeps(pool, {
+ ensureReady: async () => {
+ throw new Error(`[${code}] ${detail}`);
+ },
+ });
+ const { payload, isError } = await callParsed(makeRegistry(deps), 'ssh_exec', {
+ host: 'web-1',
+ command: 'true',
+ });
+ expect(isError).toBe(true);
+ expect(payload.errorCode).toBe(code);
+ expect(String((payload.data as Record<string, unknown>).hint)).toContain('重复');
+ if (code === 'SSH_CONFIG_AUTH_UNSUPPORTED') {
+ expect(String((payload.data as Record<string, unknown>).hint)).toContain('条件 Include');
+ }
+ });
+
+ it('redacts local credential paths from ensureReady errors', async () => {
+ const identityFile = '/Users/alice/.ssh/client-prod';
+ const host = snapshot({ id: 'web-1', identityFile });
+ const { pool } = makeFakePool([host]);
+ const { deps } = makeDeps(pool, {
+ ensureReady: async () => {
+ throw new Error(
+ `[SSH_CONFIG_AUTH_UNSUPPORTED] IdentityFile ${identityFile} has no public key`,
+ );
+ },
+ });
+ const { payload, rawText } = await callParsed(makeRegistry(deps), 'ssh_exec', {
+ host: 'web-1',
+ command: 'true',
+ });
+
+ expect(payload.errorCode).toBe('SSH_CONFIG_AUTH_UNSUPPORTED');
+ expect(String((payload.data as Record<string, unknown>).hint))
+ .toContain('IdentityFile <identity-file> has no public key');
+ expect(rawText).not.toContain('alice');
+ expect(rawText).not.toContain('client-prod');
+ });
+
+ it('redacts configured and resolved Agent endpoints from status and error payloads', async () => {
+ const literal = 'SSH_AUTH_SOCK';
+ const endpoint = '/private/tmp/com.apple.launchd.example/Listeners';
+ const host = snapshot({ id: 'web-1', identityAgent: literal });
+ host.lastError = `connect ${endpoint} failed via ${literal}`;
+ const { pool } = makeFakePool([host]);
+ const { deps } = makeDeps(pool, {
+ redactSensitiveText: (_snapshot, text) => text
+ .split(endpoint).join('<identity-agent>')
+ .split(literal).join('<identity-agent>'),
+ ensureReady: async () => {
+ throw new Error(`[SSH_AGENT_UNAVAILABLE] connect ${endpoint} failed via ${literal}`);
+ },
+ });
+ const registry = makeRegistry(deps);
+
+ const status = await callParsed(registry, 'ssh_host_status', { host: 'web-1' });
+ const execution = await callParsed(registry, 'ssh_exec', {
+ host: 'web-1',
+ command: 'true',
+ });
+ for (const rawText of [status.rawText, execution.rawText]) {
+ expect(rawText).not.toContain(endpoint);
+ expect(rawText).not.toContain(literal);
+ expect(rawText).toContain('<identity-agent>');
+ }
+ });
+
+ it('fails closed when the host redaction callback throws', async () => {
+ const endpoint = '/private/tmp/private-agent.sock';
+ const host = snapshot({ id: 'web-1' });
+ host.lastError = `connect ${endpoint} failed`;
+ const { pool } = makeFakePool([host]);
+ const logger = { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn(), trace: vi.fn() };
+ const { deps } = makeDeps(pool, {
+ logger,
+ redactSensitiveText: () => {
+ throw new Error(`redaction failed for ${endpoint}`);
+ },
+ });
+
+ const { rawText } = await callParsed(makeRegistry(deps), 'ssh_host_status', {
+ host: 'web-1',
+ });
+ expect(rawText).toContain('SSH error details are unavailable.');
+ expect(rawText).not.toContain(endpoint);
+ expect(JSON.stringify(logger.error.mock.calls)).not.toContain(endpoint);
+ });
+
it('unprefixed unknown error falls back to SSH_CONNECT_FAILED', async () => {
const { pool } = makeFakePool([snapshot({ id: 'web-1' })], async () => {
throw new Error('socket hangup');
diff --git a/packages/lizi-mcps/src/cindy_sshMcpServer.ts b/packages/lizi-mcps/src/cindy_sshMcpServer.ts
index 173ecca254..2455b41b15 100644
--- a/packages/lizi-mcps/src/cindy_sshMcpServer.ts
+++ b/packages/lizi-mcps/src/cindy_sshMcpServer.ts
@@ -45,6 +45,8 @@ const D_CALL_TOOL =
'`HOST_NOT_FOUND` = 目标主机未配置(返回已配置清单,引导用户到「设置 → 远程连接」添加);' +
'`AMBIGUOUS_HOST` = hostname 命中多台,改用 alias;' +
'`SSH_AUTH_FAILED` = 认证失败(确定性错误,不要重试,把 hint 转告用户);' +
+ '`SSH_AGENT_UNAVAILABLE` = 本机 SSH Agent 不可用(启动 Agent / ssh-add 后再试);' +
+ '`SSH_CONFIG_AUTH_UNSUPPORTED` = Cindy 暂不能安全复现该主机的部分 SSH 配置规则(确定性错误,不要重试);' +
'`SSH_CONNECT_FAILED` = 连接/执行失败;' +
'`EXEC_TIMEOUT` = 命令超时(长任务改 nohup 后台跑再轮询);' +
'`INVALID_ARGS` = zod schema 校验失败(返回 schema 自纠);' +
diff --git a/packages/lizi-mcps/src/ssh/_shared.ts b/packages/lizi-mcps/src/ssh/_shared.ts
index 3a2a26eba2..09d16e92e7 100644
--- a/packages/lizi-mcps/src/ssh/_shared.ts
+++ b/packages/lizi-mcps/src/ssh/_shared.ts
@@ -8,7 +8,7 @@
* 红线:调用方可能把密钥内联在命令里,回显会经统一日志路径落盘。
*/
-import type { SshHostSnapshotLike, SshPoolLike } from '../types.js';
+import type { SshHostSnapshotLike, SshMcpDeps, SshPoolLike } from '../types.js';
import type { SshToolResult } from './registry.js';
// ── payload helpers(与 xdt-helper/_payload.ts 同形) ───────────────────────
@@ -44,6 +44,8 @@ export type SshErrorCode =
| 'AMBIGUOUS_HOST'
| 'SSH_AUTH_FAILED'
| 'SSH_KEY_FILE_NOT_FOUND'
+ | 'SSH_AGENT_UNAVAILABLE'
+ | 'SSH_CONFIG_AUTH_UNSUPPORTED'
| 'SSH_CONNECT_FAILED'
| 'EXEC_TIMEOUT'
| 'PLUGIN_DISABLED'
@@ -52,7 +54,25 @@ export type SshErrorCode =
// ── host resolution ─────────────────────────────────────────────────────────
/** ssh_list_hosts / HOST_NOT_FOUND 候选清单共用的精简视图。 */
-export function hostBrief(s: SshHostSnapshotLike): Record<string, unknown> {
+const REDACTION_FAILURE_TEXT = 'SSH error details are unavailable.';
+
+/** Fail closed if the host redactor is unavailable; never log either input. */
+export function safeRedactSensitiveText(
+ deps: Pick<SshMcpDeps, 'redactSensitiveText'>,
+ snapshot: SshHostSnapshotLike,
+ text: string,
+): string {
+ try {
+ return deps.redactSensitiveText(snapshot, text);
+ } catch {
+ return REDACTION_FAILURE_TEXT;
+ }
+}
+
+export function hostBrief(
+ s: SshHostSnapshotLike,
+ deps: Pick<SshMcpDeps, 'redactSensitiveText'>,
+): Record<string, unknown> {
return {
id: s.config.id,
hostname: s.config.hostname,
@@ -61,7 +81,7 @@ export function hostBrief(s: SshHostSnapshotLike): Record<string, unknown> {
authMethod: s.config.authMethod,
status: s.status,
...(s.lastAuthLabel ? { lastAuthLabel: s.lastAuthLabel } : {}),
- ...(s.lastError ? { lastError: s.lastError } : {}),
+ ...(s.lastError ? { lastError: safeRedactSensitiveText(deps, s, s.lastError) } : {}),
};
}
@@ -76,7 +96,11 @@ export type ResolveHostResult =
* 3. 都没有 → HOST_NOT_FOUND,附现有主机清单引导用户去「设置 → 远程连接」添加
* (v1 刻意不支持连未配置的主机——那会退回"猜 key / 猜 agent"的老路)。
*/
-export function resolveHost(pool: SshPoolLike, nameOrIp: string): ResolveHostResult {
+export function resolveHost(
+ pool: SshPoolLike,
+ nameOrIp: string,
+ deps: Pick<SshMcpDeps, 'redactSensitiveText'>,
+): ResolveHostResult {
const snapshots = pool.list();
const byId = snapshots.find((s) => s.config.id === nameOrIp);
if (byId) return { ok: true, snapshot: byId };
@@ -89,7 +113,7 @@ export function resolveHost(pool: SshPoolLike, nameOrIp: string): ResolveHostRes
result: errorPayload(
'AMBIGUOUS_HOST',
`hostname "${nameOrIp}" 命中多台已配置主机,请改用唯一的 alias(candidates 里的 id 字段)指定。`,
- { candidates: byHostname.map(hostBrief) },
+ { candidates: byHostname.map((snapshot) => hostBrief(snapshot, deps)) },
),
};
}
@@ -99,7 +123,7 @@ export function resolveHost(pool: SshPoolLike, nameOrIp: string): ResolveHostRes
result: errorPayload(
'HOST_NOT_FOUND',
`"${nameOrIp}" 不在已配置的 SSH 主机里。请告知用户到「设置 → 远程连接」添加该主机(或确认 ~/.ssh/config 里的 alias 拼写),不要退回手拼 ssh 命令。`,
- { configuredHosts: snapshots.map(hostBrief) },
+ { configuredHosts: snapshots.map((snapshot) => hostBrief(snapshot, deps)) },
),
};
}
@@ -155,10 +179,16 @@ export interface ClassifiedSshError {
/**
* best-effort 分类 deps.ensureReady / host.exec 抛出的错误。
* 认证失败的 message 内含 authFailureHint 的可操作提示(如 ssh-copy-id 指引),
- * 原样透传进 hint 让 agent 转告用户——认证失败是确定性的,不要重试。
+ * 去掉 main-only 凭证路径后透传进 hint 让 agent 转告用户——认证失败是确定性的,
+ * 不要重试。
*/
-export function classifySshError(err: unknown): ClassifiedSshError {
- const message = err instanceof Error ? err.message : String(err);
+export function classifySshError(
+ err: unknown,
+ deps: Pick<SshMcpDeps, 'redactSensitiveText'>,
+ snapshot?: SshHostSnapshotLike,
+): ClassifiedSshError {
+ const rawMessage = err instanceof Error ? err.message : String(err);
+ const message = snapshot ? safeRedactSensitiveText(deps, snapshot, rawMessage) : rawMessage;
if (EXEC_TIMEOUT_RE.test(message)) {
return {
@@ -189,6 +219,16 @@ export function classifySshError(err: unknown): ClassifiedSshError {
// treatment the renderer toast applies.
hint: `配置的私钥文件在本机磁盘上不存在/不可读(本机路径问题,不是网络或服务端错误):${detail.replace(/^identity file not found:\s*/, '')}。请到「设置 → 远程连接」重新选择私钥或编辑主机的 Identity file 路径。`,
};
+ case 'SSH_AGENT_UNAVAILABLE':
+ return {
+ errorCode: 'SSH_AGENT_UNAVAILABLE',
+ hint: `SSH Agent 当前不可用(重复连接不会自行恢复):${detail}。请启动 ssh-agent,并用 ssh-add 加载对应私钥后重试。`,
+ };
+ case 'SSH_CONFIG_AUTH_UNSUPPORTED':
+ return {
+ errorCode: 'SSH_CONFIG_AUTH_UNSUPPORTED',
+ hint: `此主机的部分 SSH 配置规则超出 Cindy 当前支持的子集(重复连接无效,终端 SSH 仍可能成功):${detail}。请检查 Match、条件 Include、IdentityAgent、IdentitiesOnly 和公钥设置。`,
+ };
default:
return {
errorCode: 'SSH_CONNECT_FAILED',
diff --git a/packages/lizi-mcps/src/ssh/exec.ts b/packages/lizi-mcps/src/ssh/exec.ts
index 706431b20a..216dee2212 100644
--- a/packages/lizi-mcps/src/ssh/exec.ts
+++ b/packages/lizi-mcps/src/ssh/exec.ts
@@ -68,7 +68,7 @@ export function registerSshExecTool(
return errorPayload('INTERNAL', `SSH 连接池不可用:${err instanceof Error ? err.message : String(err)}`);
}
- const resolved = resolveHost(pool, host);
+ const resolved = resolveHost(pool, host, deps);
if (!resolved.ok) return resolved.result;
const hostId = resolved.snapshot.config.id;
@@ -104,7 +104,7 @@ export function registerSshExecTool(
});
} catch (err) {
// 不回显 command 原文,只落 host + 分类结果。
- const classified = classifySshError(err);
+ const classified = classifySshError(err, deps, resolved.snapshot);
deps.logger?.warn?.(
`[cindy_ssh] ssh_exec on "${hostId}" failed: ${classified.errorCode}`,
);
diff --git a/packages/lizi-mcps/src/ssh/host_status.ts b/packages/lizi-mcps/src/ssh/host_status.ts
index 14d3ca2d0d..c5612f6177 100644
--- a/packages/lizi-mcps/src/ssh/host_status.ts
+++ b/packages/lizi-mcps/src/ssh/host_status.ts
@@ -27,11 +27,11 @@ export function registerSshHostStatusTool(
handler: async ({ host }) => {
try {
const pool = await deps.getPool();
- const resolved = resolveHost(pool, host);
+ const resolved = resolveHost(pool, host, deps);
if (!resolved.ok) return resolved.result;
const s = resolved.snapshot;
return okPayload({
- host: hostBrief(s),
+ host: hostBrief(s, deps),
statusChangedAt: new Date(s.statusChangedAt).toISOString(),
});
} catch (err) {
diff --git a/packages/lizi-mcps/src/ssh/list_hosts.ts b/packages/lizi-mcps/src/ssh/list_hosts.ts
index 2868f99f68..4a0089fb31 100644
--- a/packages/lizi-mcps/src/ssh/list_hosts.ts
+++ b/packages/lizi-mcps/src/ssh/list_hosts.ts
@@ -23,7 +23,7 @@ export function registerSshListHostsTool(
handler: async () => {
try {
const pool = await deps.getPool();
- const hosts = pool.list().map(hostBrief);
+ const hosts = pool.list().map((snapshot) => hostBrief(snapshot, deps));
return okPayload({
hosts,
...(hosts.length === 0
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 22abfe6243..0cdbfd70a5 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -317,6 +317,12 @@ export interface SshHostSnapshotLike {
port: number;
user: string;
authMethod: 'agent' | 'key';
+ /** Main-only path metadata used solely to redact model-visible errors. */
+ identityFile?: string;
+ sshAuthentication?: {
+ identityAgent?: string;
+ configuredIdentityFiles?: string[];
+ };
source: 'ssh-config' | 'manual';
};
status:
@@ -374,6 +380,8 @@ export interface SshPoolLike {
export interface SshMcpDeps {
getPool(): Promise<SshPoolLike>;
ensureReady(id: string): Promise<void>;
+ /** Host-owned synchronous boundary redactor. It must not retain its inputs. */
+ redactSensitiveText(snapshot: SshHostSnapshotLike, text: string): string;
logger?: LiziMcpLogger;
}
diff --git a/packages/maker-remote-ssh/src/ConnectionPool.ts b/packages/maker-remote-ssh/src/ConnectionPool.ts
index c12882f09b..cbb44be041 100644
--- a/packages/maker-remote-ssh/src/ConnectionPool.ts
+++ b/packages/maker-remote-ssh/src/ConnectionPool.ts
@@ -3,21 +3,21 @@
* current Electron session. Keyed by host id (the SSH alias).
*
* Phase A surface:
- * - hydrate(): bulk-add hosts read from ~/.ssh/config
+ * - hydrate(): bulk-add hosts discovered from OpenSSH config
* - add() / remove() / get() / list() — registry ops
* - connect() / disconnect() — convenience wrappers
* - onAnyStatus() — single subscription that fires for all hosts
* - dispose() — bulk disconnect on app quit
*
- * The pool itself owns no persistence. Adding a host writes to
- * ~/.ssh/config via the IPC layer (sshConfig.upsertHost); the pool just
- * keeps the in-memory mirror.
+ * The pool itself owns no persistence. The IPC layer owns OpenSSH reads and
+ * narrowly-scoped managed writes; the pool only keeps the in-memory mirror.
*/
import { EventEmitter } from 'node:events';
import { RemoteHost, type RemoteHostDeps, type StatusListener } from './RemoteHost.js';
import { FileHostKeyStore, type HostKeyStore } from './hostKeys.js';
+import { effectiveAuthenticationFingerprint } from './sshAuthentication.js';
import type { HostConfig, HostSnapshot } from './types.js';
export interface ConnectionPoolDeps {
@@ -48,10 +48,17 @@ export class ConnectionPool {
/**
* Bulk replace the registry with the given configs. Existing hosts that
* still appear keep their live status; hosts removed from the input are
- * disconnected and dropped. Used at startup after reading ~/.ssh/config.
+ * disconnected and dropped. Used after reading the effective SSH host graph.
*/
async hydrate(configs: HostConfig[]): Promise<void> {
- const incoming = new Set(configs.map((c) => c.id));
+ // Validate the complete replacement before mutating/disconnecting the
+ // current pool. A malformed refresh must leave the last valid snapshot
+ // usable rather than partially applying entries before throwing.
+ const incoming = new Set<string>();
+ for (const config of configs) {
+ if (incoming.has(config.id)) throw new Error(`duplicate host id: ${config.id}`);
+ incoming.add(config.id);
+ }
// Drop hosts no longer present.
for (const [id, host] of this.hosts) {
if (!incoming.has(id)) {
@@ -63,6 +70,11 @@ export class ConnectionPool {
for (const cfg of configs) {
const existing = this.hosts.get(cfg.id);
if (existing) {
+ if (connectionFieldsChanged(existing.config, cfg)) {
+ // Never publish a new endpoint while a live ssh2 connection still
+ // targets the old hostname/user/port/credential tuple.
+ await existing.disconnect();
+ }
existing.updateConfig(cfg);
} else {
this.register(cfg);
@@ -133,3 +145,10 @@ export class ConnectionPool {
return host;
}
}
+
+function connectionFieldsChanged(left: HostConfig, right: HostConfig): boolean {
+ return left.hostname !== right.hostname
+ || left.port !== right.port
+ || left.user !== right.user
+ || effectiveAuthenticationFingerprint(left) !== effectiveAuthenticationFingerprint(right);
+}
diff --git a/packages/maker-remote-ssh/src/RemoteHost.ts b/packages/maker-remote-ssh/src/RemoteHost.ts
index 50ce7b8f90..f69e27a5dd 100644
--- a/packages/maker-remote-ssh/src/RemoteHost.ts
+++ b/packages/maker-remote-ssh/src/RemoteHost.ts
@@ -235,11 +235,16 @@ export function isAuthFailure(msg: string): boolean {
export function authFailureHint(cfg: HostConfig): string {
const portArg = cfg.port && cfg.port !== 22 ? `-p ${cfg.port} ` : '';
if (cfg.authMethod === 'agent') {
+ const pinned = !!cfg.identityFile
+ || (cfg.sshAuthentication?.allowedAgentFingerprints?.length ?? 0) > 0;
+ if (pinned) {
+ return 'SSH agent has no key the remote accepts from the configured identity set. '
+ + 'Load the matching private key with `ssh-add`, then try again.';
+ }
return `SSH agent has no key the remote accepts. Run \`ssh-copy-id ${portArg}${cfg.user}@${cfg.hostname}\` from your terminal to install your pubkey, or re-add this host with "Identity file" auth.`;
}
if (cfg.authMethod === 'key') {
- const file = cfg.identityFile ?? '(unset)';
- return `Identity file ${file} was rejected by the remote. Verify the file is the right key for ${cfg.user}@${cfg.hostname}, or run \`ssh-copy-id ${portArg}-i ${file}.pub ${cfg.user}@${cfg.hostname}\` to install it.`;
+ return `The configured identity file was rejected by the remote. Verify it is the right key for ${cfg.user}@${cfg.hostname}, or run \`ssh-copy-id ${portArg}-i <public-key-file> ${cfg.user}@${cfg.hostname}\` with its matching public key.`;
}
return `Authentication failed connecting as ${cfg.user}@${cfg.hostname}.`;
}
@@ -340,6 +345,14 @@ export class RemoteHost {
private client: Client | null = null;
private reconnectAttempts = 0;
private reconnectTimer: NodeJS.Timeout | null = null;
+ /**
+ * Monotonic connection-attempt generation. disconnect() advances it before
+ * ending the current client, so an async resolveAuth() or late ssh2 event
+ * from the previous endpoint cannot publish status or resurrect a session.
+ */
+ private connectionEpoch = 0;
+ /** The currently running connect attempt, including reconnect attempts. */
+ private inFlightConnect: Promise<void> | null = null;
/** true = user explicitly asked to disconnect; suppress auto-reconnect. */
private userDisconnected = false;
private events = new EventEmitter();
@@ -412,10 +425,15 @@ export class RemoteHost {
async connect(): Promise<void> {
if (this.status === 'ready') return;
if (this.status === 'connecting' || this.status === 'authenticating') {
- // Wait for the in-flight attempt to settle (success or fail). After
- // the await `this.status` is mutated; TS still has the pre-await
- // narrowing, so we re-read through `getStatus()`.
- await this.waitForTerminal();
+ // Share the actual in-flight attempt instead of waiting only for a
+ // future status event. A disconnect can invalidate an attempt after it
+ // has emitted its terminal status; joining the Promise guarantees that
+ // every caller still receives the cancellation/error outcome.
+ if (this.inFlightConnect) {
+ await this.inFlightConnect;
+ } else {
+ await this.waitForTerminal();
+ }
if (this.getStatus() === 'ready') return;
// Prefer the last resolveAuth error so the structured `.code` survives
// (classifyConnectFailure needs it); fall back to the string otherwise.
@@ -430,7 +448,7 @@ export class RemoteHost {
this.clearReconnectTimer();
this.userDisconnected = false;
this.reconnectAttempts = 0;
- await this.doConnect();
+ await this.startConnectAttempt();
}
/**
@@ -439,6 +457,7 @@ export class RemoteHost {
*/
async disconnect(): Promise<void> {
this.userDisconnected = true;
+ this.connectionEpoch += 1;
this.clearReconnectTimer();
this.markForwardsDisarmed();
if (this.client) {
@@ -1067,11 +1086,21 @@ export class RemoteHost {
* onError maps to `hostKeyError`). Fails closed: a missing store or a read
* error refuses the connect rather than trusting an unverified key.
*/
- private async verifyHostKey(hostKey: Buffer): Promise<boolean> {
+ private async verifyHostKey(
+ hostKey: Buffer,
+ storeKey: string,
+ isCurrentAttempt: () => boolean,
+ ): Promise<boolean> {
+ // A cancelled client must not even touch the shared TOFU store. In
+ // particular, updateConfig() may already have published a new endpoint
+ // while the old ssh2 client delivers a late hostVerifier callback.
+ if (!isCurrentAttempt()) return false;
const store = this.hostKeys;
if (!store) {
- this.hostKeyError =
- 'SSH host key verification is not configured; refusing to connect without it.';
+ if (isCurrentAttempt()) {
+ this.hostKeyError =
+ 'SSH host key verification is not configured; refusing to connect without it.';
+ }
this.log.error('ssh host key store missing — refusing connect', { id: this.id });
return false;
}
@@ -1079,36 +1108,43 @@ export class RemoteHost {
// (e.g. removed a stale entry after a legitimate server re-key) sees the
// update on reconnect without restarting the app.
store.reload();
+ if (!isCurrentAttempt()) return false;
const presented = hostKeyFingerprint(hostKey);
- const storeKey = hostKeyId(this.cfg.hostname, this.cfg.port);
let stored: string | null;
try {
stored = await store.get(storeKey);
} catch (err) {
- this.hostKeyError = `failed to read trusted host keys: ${(err as Error).message}`;
+ if (isCurrentAttempt()) {
+ this.hostKeyError = `failed to read trusted host keys: ${(err as Error).message}`;
+ }
this.log.error('ssh known-hosts read failed — refusing connect', {
id: this.id,
error: (err as Error).message,
});
return false;
}
+ if (!isCurrentAttempt()) return false;
const decision = decideHostKey(stored, presented);
if (decision === 'match') return true;
if (decision === 'trust-new') {
+ if (!isCurrentAttempt()) return false;
try {
- await store.set(storeKey, presented);
+ await store.set(storeKey, presented, isCurrentAttempt);
} catch (err) {
// Cannot persist the trusted fingerprint — refuse the connection.
// Proceeding without persistence means the next reconnect would
// re-enter trust-new and silently accept any key, defeating TOFU.
- this.hostKeyError = `failed to persist trusted host key: ${(err as Error).message}`;
+ if (isCurrentAttempt()) {
+ this.hostKeyError = `failed to persist trusted host key: ${(err as Error).message}`;
+ }
this.log.error('ssh known-hosts write failed — refusing connect', {
id: this.id,
error: (err as Error).message,
});
return false;
}
+ if (!isCurrentAttempt()) return false;
this.log.info('ssh host key trusted on first use', {
id: this.id,
host: storeKey,
@@ -1117,11 +1153,13 @@ export class RemoteHost {
return true;
}
// mismatch
- 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.`;
+ if (isCurrentAttempt()) {
+ 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.`;
+ }
this.log.error('ssh host key mismatch — refusing connect', {
id: this.id,
host: storeKey,
@@ -1132,14 +1170,38 @@ export class RemoteHost {
}
private async doConnect(): Promise<void> {
+ const attemptEpoch = ++this.connectionEpoch;
+ const isCurrentAttempt = (): boolean => attemptEpoch === this.connectionEpoch;
+ const cancelledError = (): Error => new Error('SSH connection attempt cancelled');
+ const attemptConfig: HostConfig = {
+ ...this.cfg,
+ ...(this.cfg.sshAuthentication
+ ? {
+ sshAuthentication: {
+ ...this.cfg.sshAuthentication,
+ configuredIdentityFiles: [
+ ...this.cfg.sshAuthentication.configuredIdentityFiles,
+ ],
+ ...(this.cfg.sshAuthentication.allowedAgentFingerprints
+ ? {
+ allowedAgentFingerprints: [
+ ...this.cfg.sshAuthentication.allowedAgentFingerprints,
+ ],
+ }
+ : {}),
+ },
+ }
+ : {}),
+ };
this.setStatus('connecting');
this.hostKeyError = null;
this.lastAuthError = null;
let auth;
try {
- auth = await resolveAuth(this.cfg);
+ auth = await resolveAuth(attemptConfig);
} catch (err) {
+ if (!isCurrentAttempt()) throw cancelledError();
const msg = (err as Error).message;
this.lastError = msg;
// Keep the full error so concurrent connect() joiners can rethrow it
@@ -1149,19 +1211,33 @@ export class RemoteHost {
throw err;
}
+ // disconnect() may have run while local credentials were being resolved.
+ // Do not create an ssh2 client after that cancellation boundary.
+ if (!isCurrentAttempt()) throw cancelledError();
+
+ // Unsupported configuration fails in resolveAuth above. Only a usable,
+ // fully-resolved endpoint may participate in TOFU identity calculation.
+ const attemptHostKeyId = hostKeyId(attemptConfig.hostname, attemptConfig.port);
const client = new Client();
this.client = client;
const connectConfig: ConnectConfig = {
- host: this.cfg.hostname,
- port: this.cfg.port,
- username: this.cfg.user,
+ host: attemptConfig.hostname,
+ port: attemptConfig.port,
+ username: attemptConfig.user,
readyTimeout: READY_TIMEOUT_MS,
keepaliveInterval: KEEPALIVE_INTERVAL_MS,
keepaliveCountMax: KEEPALIVE_COUNT_MAX,
// TOFU host key check — without this ssh2 trusts any presented key (MITM).
hostVerifier: (hostKey: Buffer, verify: (valid: boolean) => void): void => {
- void this.verifyHostKey(hostKey).then(verify, () => verify(false));
+ if (!isCurrentAttempt()) {
+ verify(false);
+ return;
+ }
+ void this.verifyHostKey(hostKey, attemptHostKeyId, isCurrentAttempt).then(
+ (valid) => verify(isCurrentAttempt() ? valid : false),
+ () => verify(false),
+ );
},
...(auth.agent ? { agent: auth.agent } : {}),
...(auth.privateKey ? { privateKey: auth.privateKey } : {}),
@@ -1170,8 +1246,8 @@ export class RemoteHost {
this.log.debug('ssh connecting', {
id: this.id,
- hostname: this.cfg.hostname,
- port: this.cfg.port,
+ hostname: attemptConfig.hostname,
+ port: attemptConfig.port,
auth: auth.label,
});
@@ -1180,6 +1256,12 @@ export class RemoteHost {
const onReady = () => {
if (settled) return;
+ if (!isCurrentAttempt()) {
+ settled = true;
+ try { client.end(); } catch { /* stale client is already closing */ }
+ reject(cancelledError());
+ return;
+ }
settled = true;
this.lastError = undefined;
this.lastAuthLabel = auth.label;
@@ -1193,6 +1275,13 @@ export class RemoteHost {
};
const onError = (err: Error) => {
+ if (!isCurrentAttempt()) {
+ if (!settled) {
+ settled = true;
+ reject(cancelledError());
+ }
+ return;
+ }
if (settled) {
// Post-ready error — feed into reconnect path, not the connect promise.
this.handlePostReadyError(err);
@@ -1207,7 +1296,7 @@ export class RemoteHost {
this.lastError = this.hostKeyError
? this.hostKeyError
: isAuthFailure(err.message)
- ? authFailureHint(this.cfg)
+ ? authFailureHint(attemptConfig)
: err.message;
this.client = null;
this.setStatus('failed');
@@ -1221,6 +1310,13 @@ export class RemoteHost {
};
const onClose = () => {
+ if (!isCurrentAttempt()) {
+ if (!settled) {
+ settled = true;
+ reject(cancelledError());
+ }
+ return;
+ }
if (!settled) {
settled = true;
const msg = this.lastError ?? 'connection closed before ready';
@@ -1237,7 +1333,9 @@ export class RemoteHost {
// ssh2 emits 'handshake' before 'ready' — repurpose to advance state
// so renderer can show "authenticating" instead of staying on
// "connecting" throughout auth.
- client.on('handshake', () => this.setStatus('authenticating'));
+ client.on('handshake', () => {
+ if (isCurrentAttempt()) this.setStatus('authenticating');
+ });
client.on('ready', onReady);
client.on('error', onError);
client.on('close', onClose);
@@ -1250,6 +1348,21 @@ export class RemoteHost {
});
}
+ /** Start and register a connect attempt so concurrent callers can join it. */
+ private startConnectAttempt(): Promise<void> {
+ const attempt = this.doConnect();
+ this.inFlightConnect = attempt;
+ void attempt.then(
+ () => {
+ if (this.inFlightConnect === attempt) this.inFlightConnect = null;
+ },
+ () => {
+ if (this.inFlightConnect === attempt) this.inFlightConnect = null;
+ },
+ );
+ return attempt;
+ }
+
private handlePostReadyError(err: Error): void {
this.lastError = err.message;
this.log.warn('ssh post-ready error', { id: this.id, error: err.message });
@@ -1298,10 +1411,11 @@ export class RemoteHost {
});
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
- void this.doConnect().catch((err) => {
+ void this.startConnectAttempt().catch((err) => {
// doConnect already set status=failed and recorded lastError.
// If we still have attempts left, schedule again.
- if (this.reconnectAttempts < MAX_RECONNECT_ATTEMPTS && !this.userDisconnected) {
+ if (this.userDisconnected) return;
+ if (this.reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
this.scheduleReconnect();
} else {
this.log.error('ssh reconnect exhausted', { id: this.id, error: (err as Error).message });
@@ -1341,6 +1455,9 @@ export class RemoteHost {
/** Wait until status leaves {connecting, authenticating}. */
private waitForTerminal(): Promise<void> {
+ if (this.status !== 'connecting' && this.status !== 'authenticating') {
+ return Promise.resolve();
+ }
return new Promise((resolve) => {
const off = this.onStatus((snap) => {
if (snap.status !== 'connecting' && snap.status !== 'authenticating') {
diff --git a/packages/maker-remote-ssh/src/__tests__/authFailureClassification.test.ts b/packages/maker-remote-ssh/src/__tests__/authFailureClassification.test.ts
index 9a24f4833e..4248241e69 100644
--- a/packages/maker-remote-ssh/src/__tests__/authFailureClassification.test.ts
+++ b/packages/maker-remote-ssh/src/__tests__/authFailureClassification.test.ts
@@ -25,6 +25,7 @@ function cfg(partial: Partial<HostConfig>): HostConfig {
user: 'deploy',
authMethod: 'agent',
source: 'manual',
+ managedByCindy: false,
...partial,
};
}
@@ -38,10 +39,30 @@ describe('isAuthFailure recognizes every authFailureHint variant', () => {
expect(isAuthFailure(authFailureHint(cfg({ authMethod: 'agent', port: 2222 })))).toBe(true);
});
+ it('pinned agent hint tells the user to load the matching key', () => {
+ const hint = authFailureHint(cfg({
+ authMethod: 'agent',
+ sshAuthentication: {
+ identitiesOnly: true,
+ configuredIdentityFiles: ['/home/u/.ssh/id_ed25519'],
+ identityFileDirectiveSeen: true,
+ identityFileNoneSeen: false,
+ allowedAgentFingerprints: ['SHA256:test'],
+ },
+ }));
+ expect(hint).toContain('ssh-add');
+ expect(isAuthFailure(hint)).toBe(true);
+ });
+
it('key mode hint (with and without identityFile)', () => {
- expect(
- isAuthFailure(authFailureHint(cfg({ authMethod: 'key', identityFile: '/home/u/.ssh/id_ed25519' }))),
- ).toBe(true);
+ const hint = authFailureHint(cfg({
+ authMethod: 'key',
+ identityFile: '/home/u/.ssh/custom-private.key',
+ }));
+ expect(isAuthFailure(hint)).toBe(true);
+ expect(hint).toContain('<public-key-file>');
+ expect(hint).not.toContain('/home/u/.ssh');
+ expect(hint).not.toContain('custom-private.key.pub');
expect(isAuthFailure(authFailureHint(cfg({ authMethod: 'key' })))).toBe(true);
});
diff --git a/packages/maker-remote-ssh/src/__tests__/connectionPool.test.ts b/packages/maker-remote-ssh/src/__tests__/connectionPool.test.ts
new file mode 100644
index 0000000000..dd46c8aa15
--- /dev/null
+++ b/packages/maker-remote-ssh/src/__tests__/connectionPool.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { ConnectionPool } from '../ConnectionPool.js';
+import type { HostConfig } from '../types.js';
+
+const logger = {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+};
+
+function host(id: string, hostname = '192.0.2.1'): HostConfig {
+ return {
+ id,
+ hostname,
+ port: 22,
+ user: 'developer',
+ authMethod: 'agent',
+ source: 'ssh-config',
+ managedByCindy: false,
+ };
+}
+
+describe('ConnectionPool.hydrate', () => {
+ it('validates duplicate ids before mutating the existing pool', async () => {
+ const pool = new ConnectionPool({ logger });
+ const existing = pool.add(host('keep'));
+ const disconnect = vi.spyOn(existing, 'disconnect').mockResolvedValue();
+
+ await expect(pool.hydrate([host('duplicate'), host('duplicate')]))
+ .rejects.toThrow('duplicate host id');
+
+ expect(pool.get('keep')).toBe(existing);
+ expect(disconnect).not.toHaveBeenCalled();
+ });
+
+ it('disconnects an alias before publishing changed connection fields', async () => {
+ const pool = new ConnectionPool({ logger });
+ const existing = pool.add(host('lab'));
+ const disconnect = vi.spyOn(existing, 'disconnect').mockResolvedValue();
+
+ await pool.hydrate([host('lab', '192.0.2.99')]);
+
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ expect(pool.get('lab')?.config.hostname).toBe('192.0.2.99');
+ });
+
+ it('disconnects when effective SSH agent authentication metadata changes', async () => {
+ const pool = new ConnectionPool({ logger });
+ const initial = host('lab');
+ initial.sshAuthentication = {
+ identitiesOnly: false,
+ identityAgent: '/tmp/agent-a.sock',
+ configuredIdentityFiles: [],
+ identityFileDirectiveSeen: false,
+ identityFileNoneSeen: false,
+ };
+ const existing = pool.add(initial);
+ const disconnect = vi.spyOn(existing, 'disconnect').mockResolvedValue();
+ const next = host('lab');
+ next.sshAuthentication = {
+ ...initial.sshAuthentication,
+ identityAgent: '/tmp/agent-b.sock',
+ };
+
+ await pool.hydrate([next]);
+
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('disconnects a key host when its unsupported config state changes', async () => {
+ const pool = new ConnectionPool({ logger });
+ const initial = host('lab');
+ initial.authMethod = 'key';
+ initial.identityFile = '/tmp/lab.key';
+ initial.sshAuthentication = {
+ identitiesOnly: false,
+ configuredIdentityFiles: [],
+ identityFileDirectiveSeen: false,
+ identityFileNoneSeen: false,
+ };
+ const existing = pool.add(initial);
+ const disconnect = vi.spyOn(existing, 'disconnect').mockResolvedValue();
+ const next = host('lab');
+ next.authMethod = 'key';
+ next.identityFile = '/tmp/lab.key';
+ next.sshAuthentication = {
+ ...initial.sshAuthentication,
+ unsupportedReason: 'Cindy does not evaluate a Match block that may affect this SSH host',
+ };
+
+ await pool.hydrate([next]);
+
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/maker-remote-ssh/src/__tests__/credentials.test.ts b/packages/maker-remote-ssh/src/__tests__/credentials.test.ts
index fbbe0b29c5..826573c55b 100644
--- a/packages/maker-remote-ssh/src/__tests__/credentials.test.ts
+++ b/packages/maker-remote-ssh/src/__tests__/credentials.test.ts
@@ -15,7 +15,16 @@
import { describe, expect, it } from 'vitest';
-import { KEY_FILE_NOT_FOUND_CODE, resolveAuth } from '../credentials.js';
+import {
+ KEY_FILE_NOT_FOUND_CODE,
+ resolveAuth,
+ SSH_CONFIG_AUTH_UNSUPPORTED_CODE,
+} from '../credentials.js';
+import {
+ previewAgentEndpoint,
+ resolveAgentEndpoint,
+ SSH_AGENT_UNAVAILABLE_CODE,
+} from '../sshAuthentication.js';
import type { HostConfig } from '../types.js';
function keyHost(over: Partial<HostConfig> & Pick<HostConfig, 'identityFile'>): HostConfig {
@@ -26,6 +35,7 @@ function keyHost(over: Partial<HostConfig> & Pick<HostConfig, 'identityFile'>):
user: 'admin',
authMethod: 'key',
source: 'manual',
+ managedByCindy: false,
...over,
};
}
@@ -59,4 +69,141 @@ describe('resolveAuth key-mode identityFile handling', () => {
const host = keyHost({ identityFile: process.cwd() });
await expect(resolveAuth(host)).rejects.toThrow(/failed to read identityFile .*EISDIR|failed to read identityFile/);
});
+
+ it('fails closed before reading a key when discovery marked the SSH config unsupported', async () => {
+ const host = keyHost({
+ identityFile: '/tmp/does-not-need-to-exist.key',
+ sshAuthentication: {
+ identitiesOnly: false,
+ configuredIdentityFiles: [],
+ identityFileDirectiveSeen: false,
+ identityFileNoneSeen: false,
+ unsupportedReason: 'Cindy does not evaluate a Match block that may affect this SSH host',
+ },
+ });
+
+ await expect(resolveAuth(host)).rejects.toMatchObject({
+ code: SSH_CONFIG_AUTH_UNSUPPORTED_CODE,
+ });
+ });
+});
+
+describe('resolveAuth OpenSSH agent metadata', () => {
+ it('treats only exact lowercase IdentityAgent none as the disable sentinel', () => {
+ expect(previewAgentEndpoint('none')).toMatchObject({
+ unsupportedReason: expect.stringContaining('disables SSH Agent'),
+ });
+ expect(previewAgentEndpoint('NONE')).toMatchObject({ endpoint: 'NONE' });
+ });
+
+ it('rejects unsupported IdentityAgent percent-token expansion', () => {
+ expect(previewAgentEndpoint('%d/.ssh/agent')).toMatchObject({
+ unsupportedReason: expect.stringContaining('percent-token'),
+ });
+ });
+
+ it('rejects a missing IdentityAgent environment variable', () => {
+ const name = 'CINDY_TEST_MISSING_AGENT_SOCKET';
+ const previous = process.env[name];
+ delete process.env[name];
+ try {
+ expect(previewAgentEndpoint(`$${name}`)).toMatchObject({
+ unavailableReason: expect.stringContaining('environment variable is not set'),
+ });
+ } finally {
+ if (previous !== undefined) process.env[name] = previous;
+ }
+ });
+
+ it('classifies a missing default agent endpoint as unavailable, not unsupported', async () => {
+ if (process.platform === 'win32') return;
+ const previous = process.env.SSH_AUTH_SOCK;
+ delete process.env.SSH_AUTH_SOCK;
+ try {
+ await expect(resolveAgentEndpoint()).rejects.toMatchObject({
+ code: SSH_AGENT_UNAVAILABLE_CODE,
+ });
+ } finally {
+ if (previous !== undefined) process.env.SSH_AUTH_SOCK = previous;
+ }
+ });
+
+
+ it('keeps an external IdentityFile host unfiltered when IdentitiesOnly is unset', async () => {
+ const previous = process.env.SSH_AUTH_SOCK;
+ process.env.SSH_AUTH_SOCK = '/tmp/cindy-test-agent.sock';
+ try {
+ const resolved = await resolveAuth({
+ id: 'lab',
+ hostname: '192.0.2.10',
+ port: 22,
+ user: 'developer',
+ authMethod: 'agent',
+ source: 'ssh-config',
+ managedByCindy: false,
+ sshAuthentication: {
+ identitiesOnly: false,
+ identityAgent: undefined,
+ configuredIdentityFiles: ['/Users/me/.ssh/lab.key'],
+ identityFileDirectiveSeen: true,
+ identityFileNoneSeen: false,
+ },
+ });
+ expect(resolved).toMatchObject({
+ // Windows OpenSSH uses its named pipe by default; POSIX uses the
+ // SSH_AUTH_SOCK environment variable.
+ agent: process.platform === 'win32'
+ ? '\\\\.\\pipe\\openssh-ssh-agent'
+ : '/tmp/cindy-test-agent.sock',
+ label: 'ssh-agent',
+ });
+ } finally {
+ if (previous === undefined) delete process.env.SSH_AUTH_SOCK;
+ else process.env.SSH_AUTH_SOCK = previous;
+ }
+ });
+
+ it('does not fall back to the default agent for IdentityAgent none', async () => {
+ await expect(resolveAuth({
+ id: 'disabled-agent',
+ hostname: '192.0.2.11',
+ port: 22,
+ user: 'developer',
+ authMethod: 'agent',
+ source: 'ssh-config',
+ managedByCindy: false,
+ sshAuthentication: {
+ identitiesOnly: false,
+ identityAgent: 'none',
+ configuredIdentityFiles: [],
+ identityFileDirectiveSeen: false,
+ identityFileNoneSeen: false,
+ },
+ })).rejects.toMatchObject({ code: SSH_CONFIG_AUTH_UNSUPPORTED_CODE });
+ });
+
+ it('rejects an empty IdentitiesOnly allow-list', async () => {
+ const previous = process.env.SSH_AUTH_SOCK;
+ delete process.env.SSH_AUTH_SOCK;
+ try {
+ await expect(resolveAuth({
+ id: 'empty-pin',
+ hostname: '192.0.2.12',
+ port: 22,
+ user: 'developer',
+ authMethod: 'agent',
+ source: 'ssh-config',
+ managedByCindy: false,
+ sshAuthentication: {
+ identitiesOnly: true,
+ configuredIdentityFiles: [],
+ identityFileDirectiveSeen: true,
+ identityFileNoneSeen: true,
+ },
+ })).rejects.toMatchObject({ code: SSH_CONFIG_AUTH_UNSUPPORTED_CODE });
+ } finally {
+ if (previous === undefined) delete process.env.SSH_AUTH_SOCK;
+ else process.env.SSH_AUTH_SOCK = previous;
+ }
+ });
});
diff --git a/packages/maker-remote-ssh/src/__tests__/filteredAgent.test.ts b/packages/maker-remote-ssh/src/__tests__/filteredAgent.test.ts
index 3cb4f9b488..5c718a1dfc 100644
--- a/packages/maker-remote-ssh/src/__tests__/filteredAgent.test.ts
+++ b/packages/maker-remote-ssh/src/__tests__/filteredAgent.test.ts
@@ -113,6 +113,31 @@ describe('FilteredAgent.getIdentities', () => {
expect(sshFingerprint(keys[0])).toBe(targetFingerprint);
});
+ it('returns multiple keys in configured order rather than upstream order', async () => {
+ const keyA = makeKey(Buffer.from('ordered-a'));
+ const keyB = makeKey(Buffer.from('ordered-b'));
+ const keyC = makeKey(Buffer.from('ordered-c'));
+ const filtered = new FilteredAgent(
+ new MockUpstreamAgent([keyA, keyB, keyC]),
+ [sshFingerprint(keyC), sshFingerprint(keyA), sshFingerprint(keyC)],
+ );
+
+ const keys = await new Promise<ParsedKey[]>((resolve, reject) => {
+ filtered.getIdentities((err, values) => (err ? reject(err) : resolve(values ?? [])));
+ });
+
+ expect(keys.map(sshFingerprint)).toEqual([
+ sshFingerprint(keyC),
+ sshFingerprint(keyA),
+ ]);
+ });
+
+ it('rejects an empty allow-list instead of exposing every agent identity', () => {
+ expect(() => new FilteredAgent(new MockUpstreamAgent([]), [])).toThrow(
+ 'requires at least one allowed fingerprint',
+ );
+ });
+
it('returns empty array when no upstream key matches', async () => {
const upstream = new MockUpstreamAgent([
makeKey(Buffer.from('only-key')),
diff --git a/packages/maker-remote-ssh/src/__tests__/remoteHostAuthErrorPreserved.test.ts b/packages/maker-remote-ssh/src/__tests__/remoteHostAuthErrorPreserved.test.ts
index 2a9bb8d5a9..ca99090e43 100644
--- a/packages/maker-remote-ssh/src/__tests__/remoteHostAuthErrorPreserved.test.ts
+++ b/packages/maker-remote-ssh/src/__tests__/remoteHostAuthErrorPreserved.test.ts
@@ -2,10 +2,10 @@
* RemoteHost concurrent-connect join 保留 resolveAuth 错误 code 的回归 (#1837 P1)。
*
* 背景:greptile review 指出,同一主机两个 connect 请求重叠时,后到的请求在
- * waitForTerminal 后从 `lastError` 字符串重新构造 Error,丢失 resolveAuth 打的
- * KEY_FILE_NOT_FOUND_CODE——导致缺失私钥错误回落为 SSH_CONNECT_FAILED,用户
- * 看不到路径修复指引。修复:RemoteHost 在 resolveAuth 失败时保留完整错误对象
- * (lastAuthError),并发 join 时 rethrow 它,让 .code 结构存活。
+ * 连接等待者不能从 `lastError` 字符串重新构造 Error,否则会丢失 resolveAuth
+ * 打的 KEY_FILE_NOT_FOUND_CODE——导致缺失私钥错误回落为 SSH_CONNECT_FAILED,
+ * 用户看不到路径修复指引。RemoteHost 让并发调用共享同一个 in-flight Promise,
+ * 并继续保留完整错误对象,让 .code 结构存活。
*/
import { describe, expect, it, vi } from 'vitest';
@@ -51,6 +51,7 @@ const HOST_CONFIG: HostConfig = {
authMethod: 'key',
identityFile: String.raw`C:\Users\someone\.ssh\id_ed25519`,
source: 'manual',
+ managedByCindy: false,
};
const noopLogger = {
@@ -63,7 +64,7 @@ const noopLogger = {
describe('RemoteHost concurrent connect preserves resolveAuth error code', () => {
it('the concurrent joiner rethrows the last resolveAuth error with its .code intact', async () => {
// resolveAuth 抛错(带 code),第一个 connect 让 status 进入 connecting;
- // 立刻发第二个 connect,后者走 waitForTerminal + rethrow lastAuthError。
+ // 立刻发第二个 connect,后者加入同一个 in-flight attempt。
const host = new RemoteHost(HOST_CONFIG, { logger: noopLogger });
const p1 = host.connect();
const p2 = host.connect(); // 并发 join —— resolveAuth 仍在飞,status=connecting
diff --git a/packages/maker-remote-ssh/src/__tests__/remoteHostConnectRace.test.ts b/packages/maker-remote-ssh/src/__tests__/remoteHostConnectRace.test.ts
index 9477a1bb8d..c0521987d3 100644
--- a/packages/maker-remote-ssh/src/__tests__/remoteHostConnectRace.test.ts
+++ b/packages/maker-remote-ssh/src/__tests__/remoteHostConnectRace.test.ts
@@ -16,8 +16,11 @@ class FakeClient extends EventEmitter {
forwardInPending: Array<(err: Error | undefined, port: number) => void> = [];
unforwardInCalls: Array<{ addr: string; port: number }> = [];
ended = false;
+ connectConfig: { hostVerifier?: (key: Buffer, verify: (valid: boolean) => void) => void } | null = null;
- connect(): void {}
+ connect(config?: { hostVerifier?: (key: Buffer, verify: (valid: boolean) => void) => void }): void {
+ this.connectConfig = config ?? null;
+ }
forwardIn(_addr: string, _port: number, cb: (err: Error | undefined, port: number) => void): void {
this.forwardInPending.push(cb);
}
@@ -37,20 +40,30 @@ class FakeClient extends EventEmitter {
}
}
-const h = vi.hoisted(() => ({ client: null as FakeClient | null }));
+const h = vi.hoisted(() => ({
+ client: null as FakeClient | null,
+ resolveAuth: vi.fn(async () => ({ label: 'agent' })),
+ createClient: vi.fn(),
+ hostKeyId: vi.fn((hostname: string, port: number) => `${hostname}:${port}`),
+}));
vi.mock('ssh2', () => ({
- Client: vi.fn(() => {
+ Client: h.createClient.mockImplementation(() => {
h.client = new FakeClient();
return h.client;
}),
}));
vi.mock('../credentials.js', () => ({
- resolveAuth: vi.fn(async () => ({ label: 'agent' })),
+ resolveAuth: h.resolveAuth,
defaultAgentEndpoint: vi.fn(() => ''),
}));
+vi.mock('../hostKeys.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../hostKeys.js')>();
+ return { ...actual, hostKeyId: h.hostKeyId };
+});
import { RemoteHost } from '../RemoteHost.js';
+import type { HostKeyStore } from '../hostKeys.js';
import type { HostConfig } from '../types.js';
const HOST_CONFIG: HostConfig = {
@@ -60,6 +73,7 @@ const HOST_CONFIG: HostConfig = {
user: 'deploy',
authMethod: 'agent',
source: 'manual',
+ managedByCindy: false,
};
const noopLogger = {
@@ -74,6 +88,38 @@ async function flush(): Promise<void> {
}
describe('RemoteHost arm/disconnect race', () => {
+ it('stops at the authentication guard before SSH transport or TOFU', async () => {
+ h.client = null;
+ h.createClient.mockClear();
+ h.hostKeyId.mockClear();
+ const unsupported = new Error('unsupported HostName token') as Error & { code?: string };
+ unsupported.code = 'SSH_CONFIG_AUTH_UNSUPPORTED';
+ h.resolveAuth.mockRejectedValueOnce(unsupported);
+ const store: HostKeyStore = {
+ reload: vi.fn(),
+ get: vi.fn(),
+ set: vi.fn(),
+ };
+ const host = new RemoteHost({
+ ...HOST_CONFIG,
+ sshAuthentication: {
+ identitiesOnly: false,
+ configuredIdentityFiles: [],
+ identityFileDirectiveSeen: false,
+ identityFileNoneSeen: false,
+ unsupportedReason: 'unsupported HostName token: %n',
+ },
+ }, { logger: noopLogger, hostKeys: store });
+
+ await expect(host.connect()).rejects.toMatchObject({
+ code: 'SSH_CONFIG_AUTH_UNSUPPORTED',
+ });
+ expect(h.createClient).not.toHaveBeenCalled();
+ expect(h.hostKeyId).not.toHaveBeenCalled();
+ expect(store.get).not.toHaveBeenCalled();
+ expect(store.set).not.toHaveBeenCalled();
+ });
+
it('stale forwardIn success after disconnect neither marks armed nor leaks the bind', async () => {
const host = new RemoteHost(HOST_CONFIG, { logger: noopLogger });
@@ -112,4 +158,89 @@ describe('RemoteHost arm/disconnect race', () => {
// 旧连接上刚绑上的野监听必须立刻拆除。
expect(client.unforwardInCalls).toContainEqual({ addr: '127.0.0.1', port: 47921 });
});
+
+ it('disconnect during credential resolution does not create an SSH client later', async () => {
+ h.client = null;
+ let finishAuth!: (value: { label: string }) => void;
+ h.resolveAuth.mockImplementationOnce(() => new Promise((resolve) => {
+ finishAuth = resolve;
+ }));
+ const host = new RemoteHost(HOST_CONFIG, { logger: noopLogger });
+
+ const connectP = host.connect();
+ await Promise.resolve();
+ expect(host.getStatus()).toBe('connecting');
+
+ await host.disconnect();
+ finishAuth({ label: 'agent' });
+
+ await expect(connectP).rejects.toThrow('SSH connection attempt cancelled');
+ expect(h.client).toBeNull();
+ expect(host.getStatus()).toBe('disconnected');
+ });
+
+ it('disconnect wakes concurrent connect joiners while credential resolution is still in flight', async () => {
+ h.client = null;
+ let finishAuth!: (value: { label: string }) => void;
+ h.resolveAuth.mockImplementationOnce(() => new Promise((resolve) => {
+ finishAuth = resolve;
+ }));
+ const host = new RemoteHost(HOST_CONFIG, { logger: noopLogger });
+
+ const first = host.connect();
+ const joiner = host.connect();
+ await Promise.resolve();
+ await host.disconnect();
+ finishAuth({ label: 'agent' });
+
+ await expect(first).rejects.toThrow('SSH connection attempt cancelled');
+ await expect(joiner).rejects.toThrow();
+ expect(host.getStatus()).toBe('disconnected');
+ });
+
+ 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 = {
+ reload: vi.fn(),
+ get: vi.fn(() => new Promise<string | null>((resolve) => { finishGet = resolve; })),
+ set: vi.fn(async () => undefined),
+ };
+ const host = new RemoteHost(HOST_CONFIG, { logger: noopLogger, hostKeys: store });
+ const connectP = host.connect();
+ const connectAssertion = expect(connectP).rejects.toThrow('SSH connection attempt cancelled');
+ await flush();
+ const client = h.client!;
+ const verifier = client.connectConfig?.hostVerifier;
+ expect(verifier).toBeTypeOf('function');
+ const verdict = new Promise<boolean>((resolve) => {
+ verifier!(Buffer.from('old-server-key'), resolve);
+ });
+ await Promise.resolve();
+
+ await host.disconnect();
+ host.updateConfig({ ...HOST_CONFIG, hostname: '10.0.0.99', port: 2222 });
+ finishGet(null);
+
+ await expect(verdict).resolves.toBe(false);
+ await connectAssertion;
+ expect(store.set).not.toHaveBeenCalled();
+ expect(host.snapshot().lastError).toBeUndefined();
+ });
+
+ it('disconnect before SSH ready invalidates late client events', async () => {
+ h.client = null;
+ const host = new RemoteHost(HOST_CONFIG, { logger: noopLogger });
+
+ const connectP = host.connect();
+ await flush();
+ const client = h.client!;
+ expect(client).toBeTruthy();
+
+ await host.disconnect();
+ client.emit('ready');
+
+ await expect(connectP).rejects.toThrow('SSH connection attempt cancelled');
+ expect(client.ended).toBe(true);
+ expect(host.getStatus()).toBe('disconnected');
+ });
});
diff --git a/packages/maker-remote-ssh/src/__tests__/remoteHostExecCap.test.ts b/packages/maker-remote-ssh/src/__tests__/remoteHostExecCap.test.ts
index 8d68a61f9e..bc9431b764 100644
--- a/packages/maker-remote-ssh/src/__tests__/remoteHostExecCap.test.ts
+++ b/packages/maker-remote-ssh/src/__tests__/remoteHostExecCap.test.ts
@@ -39,6 +39,7 @@ const HOST_CONFIG: HostConfig = {
user: 'deploy',
authMethod: 'agent',
source: 'manual',
+ managedByCindy: false,
};
const noopLogger = {
diff --git a/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts b/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts
index 6739913aa7..a4518a0c82 100644
--- a/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts
+++ b/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts
@@ -25,6 +25,7 @@ const HOST_CONFIG: HostConfig = {
user: 'deploy',
authMethod: 'agent',
source: 'manual',
+ managedByCindy: false,
};
const noopLogger = {
diff --git a/packages/maker-remote-ssh/src/__tests__/sshConfig.test.ts b/packages/maker-remote-ssh/src/__tests__/sshConfig.test.ts
index 0b53a00831..0059336e74 100644
--- a/packages/maker-remote-ssh/src/__tests__/sshConfig.test.ts
+++ b/packages/maker-remote-ssh/src/__tests__/sshConfig.test.ts
@@ -1,415 +1,1487 @@
-/**
- * Tests for sshConfig — read/write `~/.ssh/config` blocks.
- *
- * Why these tests matter:
- * sshConfig is the persistence layer for every host the user adds. A
- * regression in the round-trip silently corrupts `~/.ssh/config` and
- * takes down the user's normal terminal SSH too — not just ours.
- *
- * The separator regression is the load-bearing one: an earlier version
- * synthesised new directive nodes without a `separator` field, and
- * ssh-config's `toString()` emitted `IdentityFileundefined/path` which
- * was unparseable. The bug touched real user files. The
- * `updateHostFields inserts a new IdentityFile cleanly` test pins
- * that fix so it can't silently come back.
- */
-
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 SSHConfig from 'ssh-config';
import {
+ addManagedHost,
+ addManagedHostWithInclude,
+ ensureManagedConfigInclude,
expandHome,
+ MANAGED_CONFIG_MARKER,
readSshConfig,
- removeHost,
- updateHostFields,
- upsertHost,
+ readSshConfigDetailed,
+ removeManagedHost,
+ updateManagedHostFields,
} from '../sshConfig.js';
import type { HostConfig } from '../types.js';
-
-// ── per-test scratch file ────────────────────────────────────────────────────
+import type { ManagedConfigWriteToken } from '../sshConfig.js';
let scratchDir: string;
-let scratchFile: string;
+let mainConfig: string;
+let managedConfig: string;
+const TEST_PUBLIC_KEY = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPFqmiBYVCrZsGBJy/djBu4yIr1lYkTuOXI0A9vPN/lD cindy-test\n';
+const TEST_PUBLIC_KEY_2 = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIkv84ni34F924G7htx9qVI7CcGG5xYDJQoabgKUbMiv cindy-test-2\n';
beforeEach(async () => {
- scratchDir = await fs.mkdtemp(path.join(os.tmpdir(), 'sshconfig-test-'));
- scratchFile = path.join(scratchDir, 'config');
+ scratchDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-ssh-config-'));
+ mainConfig = path.join(scratchDir, 'config');
+ managedConfig = path.join(scratchDir, 'cindy.conf');
});
afterEach(async () => {
await fs.rm(scratchDir, { recursive: true, force: true });
});
-function host(over: Partial<HostConfig> & Pick<HostConfig, 'id'>): HostConfig {
+function host(overrides: Partial<HostConfig> & Pick<HostConfig, 'id'>): HostConfig {
return {
- hostname: 'example.com',
+ hostname: '192.0.2.10',
port: 22,
- user: 'me',
+ user: 'developer',
authMethod: 'agent',
source: 'ssh-config',
- ...over,
+ managedByCindy: true,
+ ...overrides,
+ };
+}
+
+async function managedWriteToken(): Promise<ManagedConfigWriteToken> {
+ await fs.writeFile(mainConfig, `Include ${managedConfig}\n`);
+ const result = await readSshConfigDetailed(mainConfig, { managedConfigPath: managedConfig });
+ expect(result.managedConfigWriteToken).toBeDefined();
+ return result.managedConfigWriteToken!;
+}
+
+function parsedIncludeEntries(raw: string): Array<{ value: string; before: string }> {
+ type ParsedNode = {
+ param?: string;
+ value?: string;
+ before?: string;
+ config?: ParsedNode[];
+ };
+ const entries: Array<{ value: string; before: string }> = [];
+ const visit = (nodes: ParsedNode[]): void => {
+ for (const node of nodes) {
+ if (node.param?.toLowerCase() === 'include') {
+ // ssh-config preserves escaped Windows backslashes in `value`; decode
+ // the serializer's one level of escaping before comparing path meaning.
+ entries.push({
+ value: path.normalize((node.value ?? '').replaceAll('\\\\', '\\')),
+ before: node.before ?? '',
+ });
+ }
+ if (node.config) visit(node.config);
+ }
};
+ visit(SSHConfig.parse(raw) as unknown as ParsedNode[]);
+ return entries;
}
-// ── readSshConfig ────────────────────────────────────────────────────────────
+describe('OpenSSH config discovery', () => {
+ it('returns an empty list for a missing main config', async () => {
+ await expect(readSshConfig(mainConfig)).resolves.toEqual([]);
+ });
-describe('readSshConfig', () => {
- it('returns empty array when the file does not exist', async () => {
- expect(await readSshConfig(scratchFile)).toEqual([]);
+ it('warns when the main config is missing but an unmanaged Cindy file exists', async () => {
+ await fs.writeFile(managedConfig, 'Host unreachable\n');
+ const result = await readSshConfigDetailed(mainConfig, { managedConfigPath: managedConfig });
+ expect(result.hosts).toEqual([]);
+ expect(result.warnings[0]).toContain('not reachable');
});
- it('recognizes Host directives case-insensitively', async () => {
- await fs.writeFile(scratchFile, [
- 'host lowercase',
- ' hostname 10.0.0.1',
- ' user alice',
- '',
- 'hOsT mixedcase',
- ' HoStNaMe 10.0.0.2',
- ' UsEr bob',
+ it('uses bare aliases and excludes wildcard, negated, and character-class patterns', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host *',
+ ' User root',
+ 'Host exact',
+ ' HostName 192.0.2.1',
+ 'Host foo? web[0-9] !blocked',
+ ' HostName 192.0.2.2',
'',
].join('\n'));
- const hosts = await readSshConfig(scratchFile);
- expect(hosts).toMatchObject([
- { id: 'lowercase', hostname: '10.0.0.1', user: 'alice' },
- { id: 'mixedcase', hostname: '10.0.0.2', user: 'bob' },
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([
+ { id: 'exact', hostname: '192.0.2.1', user: 'root', managedByCindy: false },
]);
});
- it('skips wildcard / pattern / negated host entries', async () => {
- await fs.writeFile(scratchFile, [
- 'Host *',
- ' ServerAliveInterval 60',
+ it('requires OpenSSH ? patterns to match exactly one character', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host foo',
+ ' HostName right.example',
+ 'Host foo?',
+ ' User should-not-apply',
+ ' Port 2200',
+ 'Host fooa',
+ ' HostName one-character.example',
'',
- 'Host concrete',
- ' HostName 10.0.0.1',
- ' User alice',
+ ].join('\n'));
+
+ const hosts = await readSshConfig(mainConfig);
+ expect(hosts.find((item) => item.id === 'foo')).toMatchObject({
+ hostname: 'right.example',
+ port: 22,
+ });
+ expect(hosts.find((item) => item.id === 'foo')?.user).not.toBe('should-not-apply');
+ expect(hosts.find((item) => item.id === 'fooa')).toMatchObject({
+ hostname: 'one-character.example',
+ user: 'should-not-apply',
+ port: 2200,
+ });
+ });
+
+ it('matches OpenSSH Host patterns case-sensitively', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host F*',
+ ' User uppercase-pattern',
+ 'Host * !Foo',
+ ' User not-excluded',
+ 'Host Foo',
+ ' HostName 192.0.2.44',
+ 'Host foo',
+ ' HostName 192.0.2.45',
'',
- 'Host has?wildcard',
- ' HostName 10.0.0.2',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'Foo',
+ hostname: '192.0.2.44',
+ user: 'uppercase-pattern',
+ }, {
+ id: 'foo',
+ hostname: '192.0.2.45',
+ user: 'not-excluded',
+ }]);
+ });
+
+ it('keeps token-internal hashes in aliases and IdentityFile values', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host foo#bar # alias comment',
+ ' HostName 192.0.2.2',
+ ' IdentityFile keys/id#deploy # path comment',
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'foo#bar',
+ hostname: '192.0.2.2',
+ authMethod: 'agent',
+ identityFile: undefined,
+ }]);
+ });
+
+ it('expands root Include recursively, relative to the main config directory', async () => {
+ await fs.mkdir(path.join(scratchDir, 'config.d'));
+ await fs.writeFile(mainConfig, 'Include config.d/entry.conf\n');
+ await fs.writeFile(path.join(scratchDir, 'config.d', 'entry.conf'), 'Include nested.conf\n');
+ await fs.writeFile(path.join(scratchDir, 'nested.conf'), [
+ 'Host nested',
+ ' HostName 192.0.2.3',
+ ' IdentityFile keys/nested.key',
'',
- 'Host !excluded',
- ' HostName 10.0.0.3',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'nested',
+ hostname: '192.0.2.3',
+ authMethod: 'agent',
+ identityFile: undefined,
+ }]);
+ });
+
+ it('expands environment variables in Include paths', async () => {
+ const includeDir = path.join(scratchDir, 'environment-config.d');
+ await fs.mkdir(includeDir);
+ await fs.writeFile(mainConfig, 'Include ${CINDY_TEST_SSH_CONF_DIR}/*.conf\n');
+ await fs.writeFile(path.join(includeDir, 'environment.conf'), [
+ 'Host environment-include',
+ ' HostName 192.0.2.31',
'',
].join('\n'));
- const hosts = await readSshConfig(scratchFile);
- expect(hosts.map(h => h.id)).toEqual(['concrete']);
+ const previous = process.env.CINDY_TEST_SSH_CONF_DIR;
+ process.env.CINDY_TEST_SSH_CONF_DIR = includeDir;
+
+ try {
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'environment-include',
+ hostname: '192.0.2.31',
+ }]);
+ } finally {
+ if (previous === undefined) delete process.env.CINDY_TEST_SSH_CONF_DIR;
+ else process.env.CINDY_TEST_SSH_CONF_DIR = previous;
+ }
});
-});
-// ── expandHome — Windows 路径形态 ─────────────────────────────────────────────
+ it('expands the current user name in Include home-directory paths', async () => {
+ const homeSpy = vi.spyOn(os, 'homedir').mockReturnValue(scratchDir);
+ try {
+ const includeDir = path.join(scratchDir, '.ssh', 'named-user-config.d');
+ await fs.mkdir(includeDir, { recursive: true });
+ await fs.writeFile(
+ mainConfig,
+ `Include ~${os.userInfo().username}/.ssh/named-user-config.d/*.conf\n`,
+ );
+ await fs.writeFile(path.join(includeDir, 'named-user.conf'), [
+ 'Host named-user-include',
+ ' HostName 192.0.2.32',
+ '',
+ ].join('\n'));
-describe('expandHome', () => {
- const home = os.homedir();
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'named-user-include',
+ hostname: '192.0.2.32',
+ }]);
+ } finally {
+ homeSpy.mockRestore();
+ }
+ });
+
+ it.each([
+ ['an unset environment variable', 'Include ${CINDY_TEST_MISSING_SSH_DIR}/*.conf', 'is not set'],
+ ['another user home', 'Include ~cindy-review-user-that-does-not-exist/.ssh/*.conf', 'cannot be resolved'],
+ ['a malformed environment expression', 'Include ${CINDY_TEST_SSH_DIR/*.conf', 'malformed'],
+ ])('warns and fails closed after Include with %s', async (_label, includeLine, warning) => {
+ delete process.env.CINDY_TEST_MISSING_SSH_DIR;
+ await fs.writeFile(mainConfig, `${includeLine}\nHost usable\n HostName 192.0.2.33\n`);
+
+ const result = await readSshConfigDetailed(mainConfig);
+ expect(result.hosts).toMatchObject([{
+ id: 'usable',
+ hostname: '192.0.2.33',
+ sshAuthentication: {
+ unsupportedReason: expect.stringContaining('unconditional Include'),
+ },
+ }]);
+ expect(result.warnings).toEqual(expect.arrayContaining([
+ expect.stringContaining(warning),
+ ]));
+ });
+
+ it.each(['Include config.d/*', ' Include config.d/*'])(
+ 'expands Include inside a pure Host * block regardless of indentation: %s',
+ async (includeLine) => {
+ await fs.mkdir(path.join(scratchDir, 'config.d'));
+ await fs.writeFile(mainConfig, ['Host *', includeLine, ''].join('\n'));
+ await fs.writeFile(path.join(scratchDir, 'config.d', 'lab.conf'), [
+ 'Host lab',
+ ' HostName 192.0.2.4',
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([
+ { id: 'lab', hostname: '192.0.2.4' },
+ ]);
+ },
+ );
+
+ it('treats a supported Include glob with no matches as an empty operation', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Include missing.d/*.conf',
+ 'Host usable',
+ ' HostName 192.0.2.34',
+ '',
+ ].join('\n'));
- it('expands a bare tilde', () => {
- expect(expandHome('~')).toBe(home);
+ const result = await readSshConfigDetailed(mainConfig);
+ expect(result.hosts[0]).toMatchObject({ id: 'usable', hostname: '192.0.2.34' });
+ expect(result.hosts[0]?.sshAuthentication?.unsupportedReason).toBeUndefined();
});
- it('expands POSIX-style ~/ prefix', () => {
- expect(expandHome('~/.ssh/id_ed25519')).toBe(path.join(home, '.ssh', 'id_ed25519'));
+ it('fails closed when one operand of a supported Include cannot expand', async () => {
+ await fs.writeFile(path.join(scratchDir, 'valid.conf'), 'Host included\n');
+ await fs.writeFile(mainConfig, [
+ 'Include valid.conf ${CINDY_TEST_MISSING_SSH_DIR}/missing.conf',
+ 'Host usable',
+ '',
+ ].join('\n'));
+ delete process.env.CINDY_TEST_MISSING_SSH_DIR;
+
+ const result = await readSshConfigDetailed(mainConfig);
+ expect(result.hosts.map((item) => item.id)).toEqual(['included', 'usable']);
+ for (const item of result.hosts) {
+ expect(item.sshAuthentication?.unsupportedReason).toContain('unconditional Include');
+ }
+ });
+
+ it('fails closed when a concrete Host block depends on a conditional Include', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host prod',
+ ' Include conditional.conf',
+ '',
+ ].join('\n'));
+ await fs.writeFile(path.join(scratchDir, 'conditional.conf'), [
+ 'HostName 192.0.2.55',
+ 'User deploy',
+ 'Port 2205',
+ '',
+ ].join('\n'));
+
+ const result = await readSshConfigDetailed(mainConfig);
+ expect(result.hosts).toMatchObject([{
+ id: 'prod',
+ // Ignored conditional values must never become a usable default endpoint.
+ hostname: 'prod',
+ user: os.userInfo().username,
+ port: 22,
+ sshAuthentication: {
+ unsupportedReason: expect.stringContaining('conditional Include'),
+ },
+ }]);
+ expect(result.warnings).toEqual(expect.arrayContaining([
+ expect.stringContaining('conditional Include was not expanded'),
+ ]));
});
- it('expands Windows-style ~\\ prefix', () => {
- expect(expandHome('~\\.ssh\\id_ed25519')).toBe(path.join(home, '.ssh', 'id_ed25519'));
+ it('fails closed only for aliases matched by a conditional Host scope', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host * !safe',
+ ' Include conditional.conf',
+ 'Host safe',
+ ' HostName safe.example.com',
+ 'Host risky',
+ ' HostName risky.example.com',
+ '',
+ ].join('\n'));
+ await fs.writeFile(path.join(scratchDir, 'conditional.conf'), 'Port 2205\n');
+
+ const hosts = await readSshConfig(mainConfig);
+ const safe = hosts.find((host) => host.id === 'safe');
+ const risky = hosts.find((host) => host.id === 'risky');
+ expect(safe).toMatchObject({
+ hostname: 'safe.example.com',
+ });
+ expect(safe?.sshAuthentication?.unsupportedReason).toBeUndefined();
+ expect(risky).toMatchObject({
+ hostname: 'risky.example.com',
+ sshAuthentication: {
+ unsupportedReason: expect.stringContaining('conditional Include'),
+ },
+ });
});
- it('leaves an already-absolute Windows drive path untouched (backslashes preserved)', () => {
- const p = String.raw`C:\Users\foo\.ssh\id_ed25519`;
- expect(expandHome(p)).toBe(p);
+ it('does not evaluate Match blocks or Match exec', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host target',
+ ' HostName 192.0.2.5',
+ 'Match exec "touch should-not-run"',
+ ' User attacker',
+ 'Match all',
+ ' Port 2222',
+ '',
+ ].join('\n'));
+
+ const result = await readSshConfigDetailed(mainConfig);
+ expect(result.hosts).toMatchObject([{
+ id: 'target',
+ user: os.userInfo().username,
+ port: 22,
+ sshAuthentication: {
+ unsupportedReason: expect.stringContaining('does not evaluate a Match block'),
+ },
+ }]);
+ expect(result.warnings.filter((warning) => warning.includes('Match is not evaluated')))
+ .toHaveLength(2);
});
- it('leaves forward-slash absolute paths untouched', () => {
- const p = 'C:/Users/foo/.ssh/id_ed25519';
- expect(expandHome(p)).toBe(p);
+ it('fails closed when an applicable Match block may override the endpoint', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host target',
+ 'Match originalhost target',
+ ' HostName 192.0.2.55',
+ ' User remote-user',
+ ' Port 2205',
+ '',
+ ].join('\n'));
+
+ const result = await readSshConfigDetailed(mainConfig);
+ expect(result.hosts).toMatchObject([{
+ id: 'target',
+ // The ignored Match values must never become a usable default endpoint.
+ hostname: 'target',
+ port: 22,
+ user: os.userInfo().username,
+ sshAuthentication: {
+ unsupportedReason: expect.stringContaining('does not evaluate a Match block'),
+ },
+ }]);
});
- it('leaves UNC paths untouched', () => {
- const p = String.raw`\\nas\share\keys\id_ed25519`;
- expect(expandHome(p)).toBe(p);
+ it('does not reject an alias definitely excluded by Match originalhost', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host target',
+ ' HostName 192.0.2.5',
+ 'Match originalhost other-host',
+ ' HostName 192.0.2.55',
+ '',
+ ].join('\n'));
+
+ const hosts = await readSshConfig(mainConfig);
+ expect(hosts).toMatchObject([{
+ id: 'target',
+ hostname: '192.0.2.5',
+ }]);
+ expect(hosts[0]?.sshAuthentication?.unsupportedReason).toBeUndefined();
});
- it('leaves paths with spaces untouched', () => {
- const p = String.raw`C:\Users\my name\.ssh\id_ed25519`;
- expect(expandHome(p)).toBe(p);
+ it('fails closed only when effective CanonicalizeHostname enables canonicalization', async () => {
+ await fs.writeFile(mainConfig, [
+ 'CanonicalDomains corp.example',
+ 'Host safe',
+ ' CanonicalizeHostname no',
+ ' CanonicalizeHostname yes',
+ 'Host enabled',
+ ' CanonicalizeHostname always',
+ 'Host invalid',
+ ' CanonicalizeHostname maybe',
+ '',
+ ].join('\n'));
+
+ const hosts = await readSshConfig(mainConfig);
+ expect(hosts.find((item) => item.id === 'safe')?.sshAuthentication?.unsupportedReason)
+ .toBeUndefined();
+ expect(hosts.find((item) => item.id === 'enabled')?.sshAuthentication?.unsupportedReason)
+ .toContain('canonicalization');
+ expect(hosts.find((item) => item.id === 'invalid')?.sshAuthentication?.unsupportedReason)
+ .toContain('CanonicalizeHostname value');
});
-});
-// ── upsertHost + readSshConfig round-trip ────────────────────────────────────
+ it('restores the parent Host * scope after an included file returns', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host *',
+ ' User ubuntu',
+ ' Include extra.conf',
+ ' Port 2222',
+ 'Host foo',
+ ' HostName 192.0.2.6',
+ '',
+ ].join('\n'));
+ await fs.writeFile(path.join(scratchDir, 'extra.conf'), [
+ 'Host included',
+ ' HostName 192.0.2.7',
+ '',
+ ].join('\n'));
+
+ const hosts = await readSshConfig(mainConfig);
+ expect(hosts.find((item) => item.id === 'foo')).toMatchObject({
+ user: 'ubuntu',
+ port: 2222,
+ });
+ });
-describe('upsertHost round-trip', () => {
- it('replaces an existing lowercase host block when alias collides', async () => {
- await fs.writeFile(scratchFile, [
- 'host foo',
- ' hostname old',
- ' user me',
- ' ProxyJump bastion',
+ it('restores the root scope after an included file ends in a Host block', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Include extra.conf',
+ 'Port 2200',
+ 'Host bar',
+ ' HostName 192.0.2.8',
+ '',
+ ].join('\n'));
+ await fs.writeFile(path.join(scratchDir, 'extra.conf'), [
+ 'Host foo',
+ ' HostName 192.0.2.7',
'',
].join('\n'));
- await upsertHost(host({ id: 'foo', hostname: 'new', user: 'me' }), scratchFile);
+ const hosts = await readSshConfig(mainConfig);
+ expect(hosts.find((item) => item.id === 'bar')).toMatchObject({ port: 2200 });
+ });
+
+ it('deduplicates cycles and repeated physical Include files', async () => {
+ await fs.writeFile(mainConfig, 'Include a.conf a.conf\n');
+ await fs.writeFile(path.join(scratchDir, 'a.conf'), [
+ 'Include b.conf',
+ 'Host a',
+ '',
+ ].join('\n'));
+ await fs.writeFile(path.join(scratchDir, 'b.conf'), [
+ 'Include a.conf',
+ 'Host b',
+ '',
+ ].join('\n'));
- const raw = await fs.readFile(scratchFile, 'utf8');
- expect(raw).not.toMatch(/hostname old/i);
- expect(raw).toMatch(/Host foo/);
- expect(raw).toMatch(/HostName new/);
- expect(raw).not.toMatch(/ProxyJump bastion/);
- expect(await readSshConfig(scratchFile)).toMatchObject([
- { id: 'foo', hostname: 'new' },
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([
+ { id: 'b' },
+ { id: 'a' },
]);
});
- it('round-trips an agent-only host (no IdentityFile)', async () => {
- const h = host({ id: 'foo', hostname: '10.0.0.1', user: 'alice', authMethod: 'agent' });
- await upsertHost(h, scratchFile);
- const back = await readSshConfig(scratchFile);
- expect(back).toHaveLength(1);
- expect(back[0]).toMatchObject({
+ it('applies first-value-wins to HostName/User/Port and does not chain HostName aliases', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host *',
+ ' User root',
+ ' Port 2200',
+ 'Host short',
+ ' HostName long',
+ ' User developer',
+ ' Port 2222',
+ 'Host long',
+ ' HostName 192.0.2.8',
+ '',
+ ].join('\n'));
+
+ const hosts = await readSshConfig(mainConfig);
+ expect(hosts.find((item) => item.id === 'short')).toMatchObject({
+ hostname: 'long',
+ user: 'root',
+ port: 2200,
+ });
+ });
+
+ it('expands the OpenSSH tokens supported by HostName exactly once', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host tokenized',
+ ' HostName %h.%h.example.com',
+ 'Host literal-percent',
+ ' HostName edge%%node.example.com',
+ 'Host alias%segment',
+ ' HostName %h.example.com',
+ 'Host literal%alias',
+ '',
+ ].join('\n'));
+
+ const hosts = await readSshConfig(mainConfig);
+ expect(hosts.find((item) => item.id === 'tokenized')?.hostname)
+ .toBe('tokenized.tokenized.example.com');
+ expect(hosts.find((item) => item.id === 'literal-percent')?.hostname)
+ .toBe('edge%node.example.com');
+ expect(hosts.find((item) => item.id === 'alias%segment')?.hostname)
+ .toBe('alias%segment.example.com');
+ expect(hosts.find((item) => item.id === 'literal%alias')?.hostname)
+ .toBe('literal%alias');
+ });
+
+ it.each([
+ ['an unsupported token', '%n.example.com', '%n'],
+ ['a trailing percent', 'example.com%', '%'],
+ ])('keeps but rejects a host whose HostName contains %s', async (_label, hostname, token) => {
+ await fs.writeFile(mainConfig, [
+ 'Host unsupported',
+ ` HostName ${hostname}`,
+ 'Host usable',
+ ' HostName usable.example.com',
+ '',
+ ].join('\n'));
+
+ const result = await readSshConfigDetailed(mainConfig);
+ expect(result.hosts.find((item) => item.id === 'unsupported')).toMatchObject({
+ id: 'unsupported',
+ hostname: 'unsupported',
+ sshAuthentication: {
+ unsupportedReason: expect.stringContaining(`HostName token: ${token}`),
+ },
+ });
+ expect(result.warnings).toContain(
+ `SSH host "unsupported" remains listed but unsupported because HostName uses token "${token}".`,
+ );
+ });
+
+ it('keeps ordinary IdentityFile entries as agent metadata regardless of scope', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host *',
+ ' IdentityFile ~/.ssh/id_ed25519',
+ 'Host lab',
+ ' HostName 192.0.2.9',
+ ' IdentityFile ~/.ssh/lab.key',
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'lab',
+ authMethod: 'agent',
+ identityFile: undefined,
+ sshAuthentication: {
+ configuredIdentityFiles: [
+ path.join(os.homedir(), '.ssh', 'id_ed25519'),
+ path.join(os.homedir(), '.ssh', 'lab.key'),
+ ],
+ },
+ }]);
+ });
+
+ it('keeps agent auth when IdentityFile is inherited only from Host *', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host foo',
+ ' HostName 192.0.2.10',
+ 'Host *',
+ ' IdentityFile ~/.ssh/id_ed25519',
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
id: 'foo',
- hostname: '10.0.0.1',
- user: 'alice',
- port: 22,
authMethod: 'agent',
identityFile: undefined,
- });
+ }]);
});
- it('round-trips a key-file host (authMethod=key)', async () => {
- const h = host({
- id: 'bar',
- hostname: '10.0.0.2',
- user: 'bob',
- port: 2222,
+ it('uses the same Agent-first policy for concrete IdentityFile in an Include', async () => {
+ await fs.mkdir(path.join(scratchDir, 'config.d'));
+ await fs.writeFile(mainConfig, [
+ 'Host *',
+ ' IdentityFile ~/.ssh/id_ed25519',
+ 'Include config.d/*',
+ '',
+ ].join('\n'));
+ await fs.writeFile(path.join(scratchDir, 'config.d', 'lab.conf'), [
+ 'Host lab',
+ ' HostName 192.0.2.11',
+ ' IdentityFile ~/.ssh/lab.key',
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'lab',
+ authMethod: 'agent',
+ identityFile: undefined,
+ }]);
+ });
+
+ it('does not let a later duplicate Host block change agent auth classification', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host duplicate',
+ ' HostName 192.0.2.12',
+ 'Host duplicate',
+ ' IdentityFile ~/.ssh/later.key',
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'duplicate',
+ authMethod: 'agent',
+ identityFile: undefined,
+ }]);
+ });
+
+ it('honors a marker in a read-only main-config host', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host marked',
+ ' # xdt-maker:auth=agent',
+ ' IdentityFile ~/.ssh/marked.key',
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig, { managedConfigPath: managedConfig }))
+ .resolves.toMatchObject([{
+ id: 'marked',
+ authMethod: 'agent',
+ identityFile: path.join(os.homedir(), '.ssh', 'marked.key'),
+ managedByCindy: false,
+ }]);
+ });
+
+ it('takes the auth marker only from the first concrete declaration introducing an alias', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host duplicate',
+ ' # xdt-maker:auth=key',
+ ' IdentityFile first.key',
+ 'Host duplicate',
+ ' # xdt-maker:auth=agent',
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'duplicate',
authMethod: 'key',
- identityFile: '/home/bob/.ssh/id_ed25519',
+ identityFile: path.resolve(process.cwd(), 'first.key'),
+ }]);
+ });
+
+ it('resolves relative IdentityFile values from the SSH process cwd, not the config directory', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host relative-key',
+ ' # xdt-maker:auth=key',
+ ' IdentityFile keys/id_ed25519',
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'relative-key',
+ identityFile: path.resolve(process.cwd(), 'keys/id_ed25519'),
+ }]);
+ });
+
+ it('expands IdentityFile tokens from the effective host context before resolving keys', async () => {
+ const expandedIdentity = path.join(
+ scratchDir,
+ 'resolved.example-deployer-2222-%-token-identity',
+ );
+ await fs.writeFile(`${expandedIdentity}.pub`, TEST_PUBLIC_KEY);
+ await fs.writeFile(mainConfig, [
+ 'Host token-identity',
+ ' HostName resolved.example',
+ ' User deployer',
+ ' Port 2222',
+ ' IdentitiesOnly yes',
+ ` IdentityFile ${path.join(scratchDir, '%h-%r-%p-%%-%n')}`,
+ '',
+ ].join('\n'));
+
+ const [hostConfig] = await readSshConfig(mainConfig);
+ expect(hostConfig).toMatchObject({
+ id: 'token-identity',
+ sshAuthentication: {
+ identitiesOnly: true,
+ configuredIdentityFiles: [expandedIdentity],
+ },
});
- await upsertHost(h, scratchFile);
- const back = await readSshConfig(scratchFile);
- expect(back).toHaveLength(1);
- expect(back[0]).toMatchObject({
- id: 'bar',
- hostname: '10.0.0.2',
- user: 'bob',
- port: 2222,
- authMethod: 'key',
- identityFile: '/home/bob/.ssh/id_ed25519',
+ expect(hostConfig?.sshAuthentication?.allowedAgentFingerprints).toHaveLength(1);
+ expect(hostConfig?.sshAuthentication?.unsupportedReason).toBeUndefined();
+ });
+
+ it('keeps but rejects a host whose IdentityFile contains an unsupported token', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host unsupported-identity-token',
+ ' IdentitiesOnly yes',
+ ' IdentityFile ~/.ssh/id_%f',
+ 'Host usable',
+ '',
+ ].join('\n'));
+
+ const result = await readSshConfigDetailed(mainConfig);
+ expect(result.hosts.map((hostConfig) => hostConfig.id))
+ .toEqual(['unsupported-identity-token', 'usable']);
+ expect(result.hosts[0]?.sshAuthentication?.unsupportedReason)
+ .toContain('IdentityFile token: %f');
+ expect(result.warnings).toContain(
+ 'SSH host "unsupported-identity-token" remains listed but unsupported because IdentityFile uses token "%f".',
+ );
+ });
+
+ it('keeps a no-marker IdentityFile host on unfiltered Agent without guessing .pub', async () => {
+ const labKey = path.join(scratchDir, 'lab.key');
+ await fs.writeFile(labKey, 'invalid-identity-fixture');
+ await fs.writeFile(path.join(scratchDir, 'lab.pub'), TEST_PUBLIC_KEY);
+ await fs.writeFile(mainConfig, [
+ 'Host lab',
+ ` IdentityFile ${labKey}`,
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'lab',
+ authMethod: 'agent',
+ identityFile: undefined,
+ sshAuthentication: {
+ identitiesOnly: false,
+ configuredIdentityFiles: [labKey],
+ },
+ }]);
+ });
+
+ it('does not infer a custom lab.pub sibling for lab.key when IdentitiesOnly is yes', async () => {
+ const labKey = path.join(scratchDir, 'lab.key');
+ await fs.writeFile(labKey, 'invalid-identity-fixture');
+ await fs.writeFile(path.join(scratchDir, 'lab.pub'), TEST_PUBLIC_KEY);
+ await fs.writeFile(mainConfig, [
+ 'Host lab-strict',
+ ' IdentitiesOnly yes',
+ ` IdentityFile ${labKey}`,
+ '',
+ ].join('\n'));
+
+ const [hostConfig] = await readSshConfig(mainConfig);
+ expect(hostConfig).toMatchObject({
+ id: 'lab-strict',
+ authMethod: 'agent',
+ identityFile: undefined,
+ sshAuthentication: {
+ configuredIdentityFiles: [labKey],
+ identitiesOnly: true,
+ },
});
+ expect(hostConfig?.sshAuthentication?.allowedAgentFingerprints).toBeUndefined();
+ expect(hostConfig?.sshAuthentication?.unsupportedReason).toContain(labKey);
});
- it('round-trips an agent + pinned key host (authMethod=agent, identityFile set)', async () => {
- const h = host({
- id: 'baz',
- hostname: '10.0.0.3',
- user: 'carol',
+ it('pins every explicit identity in order for IdentitiesOnly yes', async () => {
+ const first = path.join(scratchDir, 'first.key');
+ const second = path.join(scratchDir, 'second.pub');
+ await fs.writeFile(`${first}.pub`, TEST_PUBLIC_KEY);
+ await fs.writeFile(second, TEST_PUBLIC_KEY_2);
+ await fs.writeFile(mainConfig, [
+ 'Host pinned',
+ ' IdentitiesOnly yes',
+ ` IdentityFile ${first}`,
+ ' IdentityFile none',
+ ` IdentityFile ${second}`,
+ '',
+ ].join('\n'));
+
+ const [pinned] = await readSshConfig(mainConfig);
+ expect(pinned).toMatchObject({
+ id: 'pinned',
authMethod: 'agent',
- identityFile: '/home/carol/.ssh/id_ed25519.pub',
+ identityFile: undefined,
+ sshAuthentication: {
+ identitiesOnly: true,
+ configuredIdentityFiles: [first, second],
+ identityFileDirectiveSeen: true,
+ identityFileNoneSeen: true,
+ },
});
- await upsertHost(h, scratchFile);
- const back = await readSshConfig(scratchFile);
- expect(back).toHaveLength(1);
- expect(back[0].authMethod).toBe('agent');
- expect(back[0].identityFile).toBe('/home/carol/.ssh/id_ed25519.pub');
+ expect(pinned?.sshAuthentication?.allowedAgentFingerprints).toHaveLength(2);
+ expect(pinned?.sshAuthentication?.unsupportedReason).toBeUndefined();
+ });
+
+ it('fails closed when any explicit IdentitiesOnly identity has no public key', async () => {
+ const valid = path.join(scratchDir, 'valid.key');
+ const missing = path.join(scratchDir, 'missing.key');
+ await fs.writeFile(`${valid}.pub`, TEST_PUBLIC_KEY);
+ await fs.writeFile(mainConfig, [
+ 'Host incomplete',
+ ' IdentitiesOnly yes',
+ ` IdentityFile ${valid}`,
+ ` IdentityFile ${missing}`,
+ '',
+ ].join('\n'));
+
+ const [hostConfig] = await readSshConfig(mainConfig);
+ expect(hostConfig?.sshAuthentication?.allowedAgentFingerprints).toBeUndefined();
+ expect(hostConfig?.sshAuthentication?.unsupportedReason).toContain(missing);
+ });
+
+ it('treats IdentityFile none as a sentinel without clearing explicit entries', async () => {
+ const first = path.join(scratchDir, 'a.key');
+ const second = path.join(scratchDir, 'b.key');
+ await fs.writeFile(mainConfig, [
+ 'Host sentinel',
+ ` IdentityFile ${first}`,
+ ' IdentityFile NONE',
+ ` IdentityFile ${second}`,
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'sentinel',
+ authMethod: 'agent',
+ sshAuthentication: {
+ identitiesOnly: false,
+ configuredIdentityFiles: [first, second],
+ identityFileNoneSeen: true,
+ },
+ }]);
+ });
+
+ it('rejects IdentitiesOnly yes with only IdentityFile none', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host empty-pin',
+ ' IdentitiesOnly yes',
+ ' IdentityFile none',
+ '',
+ ].join('\n'));
+
+ const [hostConfig] = await readSshConfig(mainConfig);
+ expect(hostConfig?.sshAuthentication?.configuredIdentityFiles).toEqual([]);
+ expect(hostConfig?.sshAuthentication?.unsupportedReason).toContain('no identity');
+ });
+
+ it('uses first-value-wins for IdentitiesOnly across Host * and exact blocks', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host *',
+ ' IdentitiesOnly yes',
+ ' IdentityFile none',
+ 'Host inherited-yes',
+ ' IdentitiesOnly no',
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'inherited-yes',
+ sshAuthentication: {
+ identitiesOnly: true,
+ unsupportedReason: expect.any(String),
+ },
+ }]);
+ });
+
+ it('keeps an earlier exact IdentitiesOnly no ahead of a later Host * yes', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host exact-no',
+ ' IdentitiesOnly no',
+ 'Host *',
+ ' IdentitiesOnly yes',
+ ' IdentityFile none',
+ '',
+ ].join('\n'));
+
+ await expect(readSshConfig(mainConfig)).resolves.toMatchObject([{
+ id: 'exact-no',
+ sshAuthentication: {
+ identitiesOnly: false,
+ },
+ }]);
+ });
+
+ it('fails closed when a present default identity has no resolvable public key', async () => {
+ const homeSpy = vi.spyOn(os, 'homedir').mockReturnValue(scratchDir);
+ try {
+ const sshDir = path.join(scratchDir, '.ssh');
+ await fs.mkdir(sshDir);
+ await fs.writeFile(
+ path.join(sshDir, 'id_ed25519'),
+ 'invalid-identity-fixture',
+ );
+ await fs.writeFile(mainConfig, 'Host defaults\n IdentitiesOnly yes\n');
+
+ const [hostConfig] = await readSshConfig(mainConfig);
+ expect(hostConfig?.sshAuthentication?.unsupportedReason).toContain('id_ed25519');
+ expect(hostConfig?.sshAuthentication?.allowedAgentFingerprints).toBeUndefined();
+ } finally {
+ homeSpy.mockRestore();
+ }
+ });
+
+ it('pins a present default identity when its .pub sibling is valid', async () => {
+ const homeSpy = vi.spyOn(os, 'homedir').mockReturnValue(scratchDir);
+ try {
+ const sshDir = path.join(scratchDir, '.ssh');
+ await fs.mkdir(sshDir);
+ await fs.writeFile(path.join(sshDir, 'id_ed25519.pub'), TEST_PUBLIC_KEY);
+ await fs.writeFile(mainConfig, 'Host defaults\n IdentitiesOnly yes\n');
+
+ const [hostConfig] = await readSshConfig(mainConfig);
+ expect(hostConfig?.sshAuthentication?.allowedAgentFingerprints).toHaveLength(1);
+ expect(hostConfig?.sshAuthentication?.unsupportedReason).toBeUndefined();
+ } finally {
+ homeSpy.mockRestore();
+ }
+ });
+
+ it('warns for unsupported agent directives and rejects them with IdentitiesOnly yes', async () => {
+ const key = path.join(scratchDir, 'cert.key');
+ await fs.writeFile(`${key}.pub`, TEST_PUBLIC_KEY);
+ await fs.writeFile(mainConfig, [
+ 'Host warning-only',
+ ' PKCS11Provider /tmp/provider.so',
+ 'Host strict-cert',
+ ' IdentitiesOnly yes',
+ ` IdentityFile ${key}`,
+ ' CertificateFile cert.pub',
+ '',
+ ].join('\n'));
+
+ const result = await readSshConfigDetailed(mainConfig);
+ expect(result.warnings.join('\n')).toContain('pkcs11provider');
+ expect(result.hosts.find((hostConfig) => hostConfig.id === 'strict-cert')
+ ?.sshAuthentication?.unsupportedReason).toContain('CertificateFile'.toLowerCase());
+ });
+
+ it('lists each alias in Host foo bar but keeps both read-only', async () => {
+ await fs.writeFile(mainConfig, `Include ${managedConfig}\n`);
+ await fs.writeFile(managedConfig, [
+ 'Host foo bar',
+ ' HostName 192.0.2.11',
+ '',
+ ].join('\n'));
+
+ const hosts = await readSshConfig(mainConfig, { managedConfigPath: managedConfig });
+ expect(hosts).toMatchObject([
+ { id: 'foo', managedByCindy: false },
+ { id: 'bar', managedByCindy: false },
+ ]);
});
- it('replaces an existing host block when alias collides', async () => {
- await upsertHost(host({ id: 'foo', hostname: 'old', user: 'me' }), scratchFile);
- await upsertHost(host({ id: 'foo', hostname: 'new', user: 'me' }), scratchFile);
- const back = await readSshConfig(scratchFile);
- expect(back).toHaveLength(1);
- expect(back[0].hostname).toBe('new');
+ it('reports Include limits as diagnostics instead of partial host lists', async () => {
+ await fs.writeFile(mainConfig, 'Include level-1.conf\n');
+ for (let level = 1; level <= 17; level += 1) {
+ await fs.writeFile(
+ path.join(scratchDir, `level-${level}.conf`),
+ level === 17 ? 'Host too-deep\n' : `Include level-${level + 1}.conf\n`,
+ );
+ }
+
+ const result = await readSshConfigDetailed(mainConfig);
+ expect(result.hosts).toEqual([]);
+ expect(result.diagnostic).toMatchObject({ kind: 'limit' });
});
});
-// ── updateHostFields — the separator regression test ────────────────────────
+describe('managed ownership', () => {
+ it('marks only a unique single-alias declaration in the supplied managed file', async () => {
+ await fs.writeFile(mainConfig, `Include ${managedConfig}\n`);
+ await fs.writeFile(managedConfig, `${MANAGED_CONFIG_MARKER}\nHost managed\n HostName 192.0.2.20\n`);
-describe('updateHostFields', () => {
- it('inserts a new IdentityFile directive with a separator so the file is re-readable', async () => {
- // Set up: agent-only host on disk, no IdentityFile.
- await upsertHost(host({ id: 'foo', hostname: '10.0.0.1', user: 'alice', authMethod: 'agent' }), scratchFile);
+ const result = await readSshConfigDetailed(mainConfig, { managedConfigPath: managedConfig });
+ expect(result.hosts).toMatchObject([
+ { id: 'managed', source: 'ssh-config', managedByCindy: true },
+ ]);
+ expect(result.managedConfigWriteToken).toMatch(/^[a-f0-9]{64}$/);
+ });
- // Switch it to key-file mode → updateHostFields must INSERT a new
- // IdentityFile directive (separator must be set, else serializer
- // emits 'IdentityFileundefined/path/key' which is unparseable).
- await updateHostFields(host({
- id: 'foo',
- hostname: '10.0.0.1',
- user: 'alice',
- authMethod: 'key',
- identityFile: '/home/alice/.ssh/id_ed25519',
- }), scratchFile);
-
- // Regression assert #1: raw file contents have no `IdentityFileundefined`.
- const raw = await fs.readFile(scratchFile, 'utf8');
- expect(raw).not.toContain('undefined');
- expect(raw).toMatch(/IdentityFile\s+\/home\/alice\/\.ssh\/id_ed25519/);
-
- // Regression assert #2: the file is re-parseable and yields the expected host.
- const back = await readSshConfig(scratchFile);
- expect(back).toHaveLength(1);
- expect(back[0]).toMatchObject({
- id: 'foo',
- authMethod: 'key',
- identityFile: '/home/alice/.ssh/id_ed25519',
- });
+ it('does not treat a host-block comment as a managed-file ownership marker', async () => {
+ await fs.writeFile(mainConfig, `Include ${managedConfig}\n`);
+ await fs.writeFile(managedConfig, 'Host user-owned\n # xdt-maker:managed=v1\n');
+
+ const result = await readSshConfigDetailed(mainConfig, { managedConfigPath: managedConfig });
+ expect(result.hosts).toMatchObject([{ id: 'user-owned', managedByCindy: false }]);
+ expect(result.managedConfigWriteToken).toBeUndefined();
});
- it('removes IdentityFile + IdentitiesOnly when switching back to agent', async () => {
- await upsertHost(host({
- id: 'foo',
- hostname: '10.0.0.1',
- user: 'alice',
- authMethod: 'key',
- identityFile: '/home/alice/.ssh/id_ed25519',
- }), scratchFile);
+ it('keeps managed aliases read-only when duplicated in any other file', async () => {
+ await fs.writeFile(mainConfig, [
+ `Include ${managedConfig}`,
+ 'Include external.conf',
+ '',
+ ].join('\n'));
+ await fs.writeFile(managedConfig, 'Host duplicate\n HostName 192.0.2.21\n');
+ await fs.writeFile(path.join(scratchDir, 'external.conf'), 'Host duplicate\n');
- await updateHostFields(host({
- id: 'foo',
- hostname: '10.0.0.1',
- user: 'alice',
- authMethod: 'agent',
- }), scratchFile);
+ await expect(readSshConfig(mainConfig, { managedConfigPath: managedConfig }))
+ .resolves.toMatchObject([{ id: 'duplicate', managedByCindy: false }]);
+ });
- const raw = await fs.readFile(scratchFile, 'utf8');
- expect(raw).not.toMatch(/IdentityFile/);
- expect(raw).not.toMatch(/IdentitiesOnly/);
+ it('marks every host read-only when managedConfigPath is omitted', async () => {
+ await fs.writeFile(mainConfig, `Include ${managedConfig}\n`);
+ await fs.writeFile(managedConfig, 'Host managed\n');
- const back = await readSshConfig(scratchFile);
- expect(back[0].authMethod).toBe('agent');
- expect(back[0].identityFile).toBeUndefined();
+ const result = await readSshConfigDetailed(mainConfig);
+ expect(result.hosts).toMatchObject([{ id: 'managed', managedByCindy: false }]);
+ expect(result.managedConfigWriteToken).toBeUndefined();
});
- it('preserves hand-written directives the user added (ProxyJump, ServerAliveInterval)', async () => {
- // Seed: a host with extra directives the user manually wrote.
- await fs.writeFile(scratchFile, [
- 'Host foo',
- ' HostName 10.0.0.1',
- ' User alice',
- ' ProxyJump bastion',
- ' ServerAliveInterval 60',
+ it('warns without discovering an existing managed file that is not Included', async () => {
+ await fs.writeFile(mainConfig, 'Host external\n');
+ await fs.writeFile(managedConfig, 'Host unreachable\n');
+
+ const result = await readSshConfigDetailed(mainConfig, { managedConfigPath: managedConfig });
+ expect(result.hosts.map((item) => item.id)).toEqual(['external']);
+ expect(result.warnings).toEqual(expect.arrayContaining([
+ expect.stringContaining('not reachable'),
+ ]));
+ });
+
+ it('warns when a later Include glob reaches the managed file again', async () => {
+ await fs.writeFile(mainConfig, [
+ `Include ${managedConfig}`,
+ `Include ${path.join(scratchDir, '*.conf')}`,
'',
].join('\n'));
+ await fs.writeFile(managedConfig, 'Host managed\n');
- // Surgical update — change port only.
- await updateHostFields(host({
- id: 'foo',
- hostname: '10.0.0.1',
- user: 'alice',
- port: 2222,
- authMethod: 'agent',
- }), scratchFile);
+ const result = await readSshConfigDetailed(mainConfig, { managedConfigPath: managedConfig });
+ expect(result.hosts.map((item) => item.id)).toEqual(['managed']);
+ expect(result.warnings).toEqual(expect.arrayContaining([
+ expect.stringContaining('already loaded'),
+ ]));
+ });
+});
- const raw = await fs.readFile(scratchFile, 'utf8');
- expect(raw).toMatch(/ProxyJump\s+bastion/);
- expect(raw).toMatch(/ServerAliveInterval\s+60/);
- expect(raw).toMatch(/Port\s+2222/);
+describe('managed config writers', () => {
+ it('inserts one canonical Include after leading comments/blanks and before Host *', async () => {
+ await fs.writeFile(mainConfig, [
+ '# user comment',
+ '',
+ 'Host *',
+ ' User ubuntu',
+ ` Include="${managedConfig}"`,
+ `Include ${path.join(scratchDir, '*.conf')}`,
+ '',
+ ].join('\n'));
+
+ await ensureManagedConfigInclude(mainConfig, managedConfig);
+ const raw = await fs.readFile(mainConfig, 'utf8');
+ expect(raw).toContain('# user comment');
+ expect(raw).toContain('Host *');
+ expect(parsedIncludeEntries(raw)).toEqual(expect.arrayContaining([
+ { value: path.normalize(managedConfig), before: '' },
+ { value: path.normalize(path.join(scratchDir, '*.conf')), before: '' },
+ ]));
});
- it('updates a lowercase host block without replacing hand-written directives', async () => {
- await fs.writeFile(scratchFile, [
- 'host foo',
- ' hostname 10.0.0.1',
- ' user alice',
- ' ProxyJump bastion',
+ it('recognizes equivalent exact Include forms, deduplicates them, and preserves comments', async () => {
+ await fs.writeFile(mainConfig, [
+ '# header',
+ 'Include=cindy.conf # keep relative note',
+ `Include "${managedConfig}" # keep duplicate note`,
+ 'Host foo',
'',
].join('\n'));
- await updateHostFields(host({
- id: 'foo',
- hostname: '10.0.0.2',
- user: 'bob',
- port: 2222,
- authMethod: 'agent',
- }), scratchFile);
-
- const raw = await fs.readFile(scratchFile, 'utf8');
- expect(raw).toMatch(/^host foo/m);
- expect(raw).toMatch(/HostName\s+10\.0\.0\.2/i);
- expect(raw).toMatch(/User\s+bob/i);
- expect(raw).toMatch(/Port\s+2222/i);
- expect(raw).toMatch(/ProxyJump\s+bastion/);
-
- const back = await readSshConfig(scratchFile);
- expect(back).toMatchObject([
- { id: 'foo', hostname: '10.0.0.2', user: 'bob', port: 2222 },
+ await ensureManagedConfigInclude(mainConfig, managedConfig);
+ const raw = await fs.readFile(mainConfig, 'utf8');
+ expect(parsedIncludeEntries(raw)).toEqual([
+ { value: path.normalize(managedConfig), before: '' },
]);
+ expect(raw).toContain('# keep relative note');
+ expect(raw).toContain('# keep duplicate note');
+ expect(raw).toContain('Host foo');
});
- it('upserts when the host block does not exist on disk', async () => {
- // Empty file → updateHostFields should fall back to upsertHost rather than throw.
- await fs.writeFile(scratchFile, '');
- await updateHostFields(host({ id: 'fresh', hostname: '10.0.0.9', user: 'me' }), scratchFile);
- const back = await readSshConfig(scratchFile);
- expect(back).toHaveLength(1);
- expect(back[0].id).toBe('fresh');
+ it('does not move an exact Include from Host foo and adds a root Include', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host foo',
+ ` Include ${managedConfig}`,
+ '',
+ ].join('\n'));
+
+ await ensureManagedConfigInclude(mainConfig, managedConfig);
+ const raw = await fs.readFile(mainConfig, 'utf8');
+ expect(parsedIncludeEntries(raw)).toEqual([
+ { value: path.normalize(managedConfig), before: '' },
+ { value: path.normalize(managedConfig), before: ' ' },
+ ]);
+ expect(raw).toContain('Host foo');
});
- it('toggles the auth marker so agent-pinned vs key is recoverable on re-read', async () => {
- // First write as agent + pinned key.
- await upsertHost(host({
- id: 'foo',
- hostname: '10.0.0.1',
- user: 'alice',
+ it('preserves CRLF and file permissions in the main config', async () => {
+ await fs.writeFile(mainConfig, '# comment\r\nHost foo\r\n', { mode: 0o640 });
+ await fs.chmod(mainConfig, 0o640);
+ const modeBefore = (await fs.stat(mainConfig)).mode & 0o777;
+
+ await ensureManagedConfigInclude(mainConfig, managedConfig);
+ const raw = await fs.readFile(mainConfig, 'utf8');
+ expect(parsedIncludeEntries(raw)).toEqual([
+ { value: path.normalize(managedConfig), before: '' },
+ ]);
+ expect(raw.replace(/\r\n/g, '')).not.toContain('\n');
+ if (modeBefore === 0o640) {
+ expect((await fs.stat(mainConfig)).mode & 0o777).toBe(modeBefore);
+ }
+ });
+
+ it('does not overwrite a concurrent edit while publishing the managed Include', async () => {
+ const original = '# original\nHost existing\n';
+ const concurrent = '# edited externally\nHost existing\n User external\n';
+ await fs.writeFile(mainConfig, original);
+ const writeFile = fs.writeFile.bind(fs);
+ const writeSpy = vi.spyOn(fs, 'writeFile').mockImplementation(async (file, data, options) => {
+ const result = await writeFile(file, data, options);
+ if (String(file).includes('.config.cindy-')) {
+ await writeFile(mainConfig, concurrent);
+ }
+ return result;
+ });
+
+ try {
+ await expect(ensureManagedConfigInclude(mainConfig, managedConfig))
+ .rejects.toMatchObject({ code: 'SSH_CONFIG_CONCURRENT_MODIFICATION' });
+ await expect(fs.readFile(mainConfig, 'utf8')).resolves.toBe(concurrent);
+ } finally {
+ writeSpy.mockRestore();
+ }
+ });
+
+ it('writes through an existing symlink without replacing the link', async ({ skip }) => {
+ const target = path.join(scratchDir, 'real-config');
+ await fs.writeFile(target, 'Host foo\n');
+ try {
+ await fs.symlink(target, mainConfig);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === 'EPERM' || code === 'EACCES') return skip();
+ throw error;
+ }
+
+ await ensureManagedConfigInclude(mainConfig, managedConfig);
+ expect((await fs.lstat(mainConfig)).isSymbolicLink()).toBe(true);
+ const raw = await fs.readFile(target, 'utf8');
+ expect(parsedIncludeEntries(raw)).toEqual([
+ { value: path.normalize(managedConfig), before: '' },
+ ]);
+ });
+
+ it('rejects a broken symlink instead of replacing it', async ({ skip }) => {
+ try {
+ await fs.symlink(path.join(scratchDir, 'missing-target'), mainConfig);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === 'EPERM' || code === 'EACCES') return skip();
+ throw error;
+ }
+ await expect(ensureManagedConfigInclude(mainConfig, managedConfig)).rejects.toThrow();
+ expect((await fs.lstat(mainConfig)).isSymbolicLink()).toBe(true);
+ });
+
+ it('adds a marked host, rereads it as managed, and removes it', async () => {
+ await fs.writeFile(mainConfig, `Include ${managedConfig}\n`);
+ await addManagedHost(host({
+ id: 'new-host',
authMethod: 'agent',
- identityFile: '/home/alice/.ssh/id_ed25519.pub',
- }), scratchFile);
- let back = await readSshConfig(scratchFile);
- expect(back[0].authMethod).toBe('agent');
+ identityFile: '/tmp/id_ed25519.pub',
+ }), managedConfig);
- // Toggle to key mode (same identityFile path on disk).
- await updateHostFields(host({
- id: 'foo',
- hostname: '10.0.0.1',
- user: 'alice',
+ const raw = await fs.readFile(managedConfig, 'utf8');
+ expect(raw).toContain('# xdt-maker:auth=agent');
+ await expect(readSshConfig(mainConfig, { managedConfigPath: managedConfig }))
+ .resolves.toMatchObject([{
+ id: 'new-host',
+ source: 'ssh-config',
+ managedByCindy: true,
+ authMethod: 'agent',
+ }]);
+
+ await removeManagedHost('new-host', managedConfig, await managedWriteToken());
+ await expect(fs.readFile(managedConfig, 'utf8')).resolves.toBe(`${MANAGED_CONFIG_MARKER}\n`);
+ });
+
+ it('quotes managed IdentityFile values without losing spaces, hashes, quotes, or backslashes', async () => {
+ const identityFile = path.join(scratchDir, 'My Keys', 'id#deploy"copy\\final');
+ await fs.writeFile(mainConfig, `Include ${managedConfig}\n`);
+ await addManagedHost(host({
+ id: 'special#alias',
authMethod: 'key',
- identityFile: '/home/alice/.ssh/id_ed25519',
- }), scratchFile);
- back = await readSshConfig(scratchFile);
- expect(back[0].authMethod).toBe('key');
+ identityFile,
+ }), managedConfig);
+
+ const raw = await fs.readFile(managedConfig, 'utf8');
+ expect(raw).toContain('IdentityFile "');
+ await expect(readSshConfig(mainConfig, { managedConfigPath: managedConfig }))
+ .resolves.toMatchObject([{
+ id: 'special#alias',
+ authMethod: 'key',
+ identityFile,
+ }]);
});
-});
-// ── removeHost ───────────────────────────────────────────────────────────────
+ it('does not publish an Include for a malformed pre-existing managed file', async () => {
+ const originalMain = 'Host external\n HostName 192.0.2.50\n';
+ await fs.writeFile(mainConfig, originalMain);
+ await fs.writeFile(managedConfig, `${MANAGED_CONFIG_MARKER}\nHost broken\n IdentityFile "unterminated\n`);
-describe('removeHost', () => {
- it('removes a lowercase host block', async () => {
- await fs.writeFile(scratchFile, [
- 'hOsT foo',
- ' HoStNaMe 10.0.0.1',
- ' User alice',
+ await expect(addManagedHostWithInclude(host({ id: 'new-host' }), mainConfig, managedConfig))
+ .rejects.toThrow();
+ await expect(fs.readFile(mainConfig, 'utf8')).resolves.toBe(originalMain);
+ });
+
+ it('does not claim a non-empty unmarked managed path', async () => {
+ const originalMain = 'Host external\n HostName 192.0.2.50\n';
+ const unownedManaged = 'Host user-owned\n HostName 192.0.2.51\n';
+ await fs.writeFile(mainConfig, originalMain);
+ await fs.writeFile(managedConfig, unownedManaged);
+
+ await expect(addManagedHostWithInclude(host({ id: 'new-host' }), mainConfig, managedConfig))
+ .rejects.toMatchObject({ code: 'SSH_CONFIG_OWNERSHIP_REQUIRED' });
+ await expect(fs.readFile(mainConfig, 'utf8')).resolves.toBe(originalMain);
+ await expect(fs.readFile(managedConfig, 'utf8')).resolves.toBe(unownedManaged);
+ });
+
+ it('stamps a newly created managed file with its ownership marker', async () => {
+ await fs.writeFile(mainConfig, '');
+
+ await addManagedHostWithInclude(host({ id: 'new-host' }), mainConfig, managedConfig);
+
+ await expect(fs.readFile(managedConfig, 'utf8')).resolves.toMatch(/^# xdt-maker:managed=v1\n/);
+ });
+
+ it('restores managed bytes when publishing the Include fails', async ({ skip }) => {
+ const originalManaged = `${MANAGED_CONFIG_MARKER}\nHost existing\n HostName 192.0.2.60\n`;
+ await fs.writeFile(managedConfig, originalManaged);
+ try {
+ await fs.symlink(path.join(scratchDir, 'missing-main-target'), mainConfig);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === 'EPERM' || code === 'EACCES') return skip();
+ throw error;
+ }
+
+ await expect(addManagedHostWithInclude(host({ id: 'new-host' }), mainConfig, managedConfig))
+ .rejects.toThrow();
+ await expect(fs.readFile(managedConfig, 'utf8')).resolves.toBe(originalManaged);
+ expect((await fs.lstat(mainConfig)).isSymbolicLink()).toBe(true);
+ });
+
+ it('returns a conditional rollback receipt for a published managed host', async () => {
+ const originalManaged = `${MANAGED_CONFIG_MARKER}\nHost existing\n HostName 192.0.2.60\n`;
+ await fs.writeFile(mainConfig, '');
+ await fs.writeFile(managedConfig, originalManaged);
+
+ const receipt = await addManagedHostWithInclude(
+ host({ id: 'new-host' }),
+ mainConfig,
+ managedConfig,
+ );
+ expect(await fs.readFile(managedConfig, 'utf8')).not.toBe(originalManaged);
+ await expect(receipt.rollback()).resolves.toBe(true);
+ await expect(fs.readFile(managedConfig, 'utf8')).resolves.toBe(originalManaged);
+ });
+
+ it('does not roll back over an external managed-file edit', async () => {
+ const originalManaged = `${MANAGED_CONFIG_MARKER}\nHost existing\n HostName 192.0.2.60\n`;
+ await fs.writeFile(mainConfig, '');
+ await fs.writeFile(managedConfig, originalManaged);
+
+ const receipt = await addManagedHostWithInclude(
+ host({ id: 'new-host' }),
+ mainConfig,
+ managedConfig,
+ );
+ await fs.appendFile(managedConfig, '# external edit\n');
+
+ await expect(receipt.rollback()).resolves.toBe(false);
+ await expect(fs.readFile(managedConfig, 'utf8')).resolves.toContain('# external edit');
+ await expect(fs.readFile(managedConfig, 'utf8')).resolves.toContain('Host new-host');
+ });
+
+ it('keeps an unpinned managed agent host as agent when Host * supplies a key', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host *',
+ ' IdentityFile ~/.ssh/id_ed25519',
+ `Include ${managedConfig}`,
'',
- 'Host bar',
- ' HostName 10.0.0.2',
- ' User bob',
+ ].join('\n'));
+ await addManagedHost(host({
+ id: 'agent-host',
+ authMethod: 'agent',
+ identityFile: undefined,
+ }), managedConfig);
+
+ await expect(fs.readFile(managedConfig, 'utf8')).resolves.toContain('# xdt-maker:auth=agent');
+ await expect(readSshConfig(mainConfig, { managedConfigPath: managedConfig }))
+ .resolves.toMatchObject([{
+ id: 'agent-host',
+ authMethod: 'agent',
+ identityFile: undefined,
+ managedByCindy: true,
+ }]);
+ });
+
+ it.each(['ProxyJump bastion', 'ProxyCommand ssh -W %h:%p bastion'])
+ ('marks an unsupported SSH transport directive as unsupported: %s', async (directive) => {
+ await fs.writeFile(mainConfig, [
+ `Host proxied-${directive.startsWith('ProxyJump') ? 'jump' : 'command'}`,
+ ` ${directive}`,
+ '',
+ ].join('\n'));
+
+ const [hostConfig] = await readSshConfig(mainConfig);
+ expect(hostConfig?.sshAuthentication?.unsupportedReason).toContain('transport');
+ });
+
+ it('treats ProxyJump/ProxyCommand none as disabled transport directives', async () => {
+ await fs.writeFile(mainConfig, [
+ 'Host direct',
+ ' ProxyJump none',
+ ' ProxyCommand none',
'',
].join('\n'));
- await removeHost('foo', scratchFile);
+ const [hostConfig] = await readSshConfig(mainConfig);
+ expect(hostConfig?.id).toBe('direct');
+ expect(hostConfig?.sshAuthentication?.unsupportedReason).toBeUndefined();
+ });
- expect(await readSshConfig(scratchFile)).toMatchObject([
- { id: 'bar', hostname: '10.0.0.2', user: 'bob' },
- ]);
+ it('fails closed when a wildcard scope supplies an unsupported proxy transport', async () => {
+ await fs.mkdir(path.join(scratchDir, 'config.d'));
+ await fs.writeFile(mainConfig, [
+ 'Host *',
+ ' ProxyJump bastion',
+ 'Include config.d/*',
+ '',
+ ].join('\n'));
+ await fs.writeFile(path.join(scratchDir, 'config.d', 'remote.conf'), [
+ 'Host remote',
+ ' HostName 192.0.2.80',
+ '',
+ ].join('\n'));
+
+ const [hostConfig] = await readSshConfig(mainConfig);
+ expect(hostConfig?.id).toBe('remote');
+ expect(hostConfig?.sshAuthentication?.unsupportedReason).toContain('proxyjump');
});
- it('drops the named host block', async () => {
- await upsertHost(host({ id: 'a' }), scratchFile);
- await upsertHost(host({ id: 'b' }), scratchFile);
- await removeHost('a', scratchFile);
- const back = await readSshConfig(scratchFile);
- expect(back.map(h => h.id)).toEqual(['b']);
+ it('surgically updates owned fields without deleting ProxyJump or other directives', async () => {
+ await fs.writeFile(managedConfig, [
+ MANAGED_CONFIG_MARKER,
+ 'Host lab',
+ ' HostName 192.0.2.30',
+ ' User alice',
+ ' ProxyJump bastion',
+ ' ServerAliveInterval 60',
+ '',
+ ].join('\n'));
+
+ const token = await managedWriteToken();
+ await updateManagedHostFields(host({
+ id: 'lab',
+ hostname: '192.0.2.31',
+ user: 'bob',
+ port: 2222,
+ authMethod: 'key',
+ identityFile: '/tmp/lab.key',
+ }), managedConfig, token);
+
+ const raw = await fs.readFile(managedConfig, 'utf8');
+ expect(raw).toContain('ProxyJump bastion');
+ expect(raw).toContain('ServerAliveInterval 60');
+ expect(raw).toContain('HostName 192.0.2.31');
+ expect(raw).toContain('Port 2222');
+ expect(raw).toContain('# xdt-maker:auth=key');
});
- it('is a no-op when the host is absent', async () => {
- await upsertHost(host({ id: 'a' }), scratchFile);
- await removeHost('nonexistent', scratchFile);
- const back = await readSshConfig(scratchFile);
- expect(back.map(h => h.id)).toEqual(['a']);
+ it('preserves CRLF and permissions while updating a managed host', async () => {
+ await fs.writeFile(managedConfig, [
+ MANAGED_CONFIG_MARKER,
+ 'Host lab',
+ ' HostName 192.0.2.40',
+ ' User alice',
+ '',
+ ].join('\r\n'), { mode: 0o640 });
+ await fs.chmod(managedConfig, 0o640);
+ const modeBefore = (await fs.stat(managedConfig)).mode & 0o777;
+
+ const token = await managedWriteToken();
+ await updateManagedHostFields(host({
+ id: 'lab',
+ hostname: '192.0.2.41',
+ user: 'bob',
+ port: 2222,
+ }), managedConfig, token);
+
+ const raw = await fs.readFile(managedConfig, 'utf8');
+ expect(raw).toContain('HostName 192.0.2.41\r\n');
+ expect(raw).toContain('Port 2222\r\n');
+ expect(raw.replace(/\r\n/g, '')).not.toContain('\n');
+ if (modeBefore === 0o640) {
+ expect((await fs.stat(managedConfig)).mode & 0o777).toBe(modeBefore);
+ }
});
- it('is a no-op when the file is missing entirely', async () => {
- // No setup — file doesn't exist.
- await expect(removeHost('any', scratchFile)).resolves.not.toThrow();
+ it('rejects update when the managed file changed after preflight', async () => {
+ await fs.writeFile(managedConfig, [
+ MANAGED_CONFIG_MARKER,
+ 'Host lab',
+ ' HostName 192.0.2.40',
+ '',
+ ].join('\n'));
+ const token = await managedWriteToken();
+ const external = `${await fs.readFile(managedConfig, 'utf8')}# external edit\n`;
+ await fs.writeFile(managedConfig, external);
+
+ await expect(updateManagedHostFields(host({ id: 'lab' }), managedConfig, token))
+ .rejects.toMatchObject({ code: 'SSH_CONFIG_CONCURRENT_MODIFICATION' });
+ await expect(fs.readFile(managedConfig, 'utf8')).resolves.toBe(external);
+ });
+
+ it('rejects remove when the managed file changed after preflight', async () => {
+ await fs.writeFile(managedConfig, [
+ MANAGED_CONFIG_MARKER,
+ 'Host lab',
+ ' HostName 192.0.2.40',
+ '',
+ ].join('\n'));
+ const token = await managedWriteToken();
+ const external = `${await fs.readFile(managedConfig, 'utf8')}# external edit\n`;
+ await fs.writeFile(managedConfig, external);
+
+ await expect(removeManagedHost('lab', managedConfig, token))
+ .rejects.toMatchObject({ code: 'SSH_CONFIG_CONCURRENT_MODIFICATION' });
+ await expect(fs.readFile(managedConfig, 'utf8')).resolves.toBe(external);
+ });
+
+ it('treats a missing managed write token as an internal package contract error', async () => {
+ await fs.writeFile(managedConfig, `${MANAGED_CONFIG_MARKER}\nHost lab\n`);
+ await expect(removeManagedHost(
+ 'lab',
+ managedConfig,
+ undefined as unknown as ManagedConfigWriteToken,
+ )).rejects.toMatchObject({ code: 'SSH_CONFIG_WRITE_TOKEN_REQUIRED' });
+ });
+});
+
+describe('expandHome', () => {
+ it('expands POSIX and Windows tilde forms', () => {
+ expect(expandHome('~/.ssh/id_ed25519')).toBe(path.join(os.homedir(), '.ssh', 'id_ed25519'));
+ expect(expandHome('~\\.ssh\\id_ed25519')).toBe(path.join(os.homedir(), '.ssh', 'id_ed25519'));
});
});
diff --git a/packages/maker-remote-ssh/src/__tests__/sshRedaction.test.ts b/packages/maker-remote-ssh/src/__tests__/sshRedaction.test.ts
new file mode 100644
index 0000000000..dfbd695704
--- /dev/null
+++ b/packages/maker-remote-ssh/src/__tests__/sshRedaction.test.ts
@@ -0,0 +1,77 @@
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { previewAgentEndpoint } from '../sshAuthentication.js';
+import { redactSshSensitiveText } from '../sshRedaction.js';
+import type { HostConfig } from '../types.js';
+
+const originalAgent = process.env.SSH_AUTH_SOCK;
+
+afterEach(() => {
+ if (originalAgent === undefined) delete process.env.SSH_AUTH_SOCK;
+ else process.env.SSH_AUTH_SOCK = originalAgent;
+});
+
+function config(identityAgent?: string): HostConfig {
+ return {
+ id: 'lab',
+ hostname: 'lab',
+ port: 22,
+ user: 'developer',
+ authMethod: 'agent',
+ identityFile: '/private/tmp/agent/identity',
+ sshAuthentication: {
+ identitiesOnly: false,
+ ...(identityAgent !== undefined ? { identityAgent } : {}),
+ configuredIdentityFiles: ['/private/tmp/agent/identity.pub'],
+ identityFileDirectiveSeen: true,
+ identityFileNoneSeen: false,
+ },
+ source: 'ssh-config',
+ managedByCindy: false,
+ };
+}
+
+describe('redactSshSensitiveText', () => {
+ it('redacts IdentityAgent literals, expanded endpoints, and overlapping identity paths', () => {
+ process.env.SSH_AUTH_SOCK = '/private/tmp/com.apple.launchd.example/Listeners';
+ const text = [
+ 'SSH_AUTH_SOCK',
+ '/private/tmp/com.apple.launchd.example/Listeners',
+ '/private/tmp/agent/identity.pub',
+ '/private/tmp/agent/identity',
+ ].join(' ');
+
+ const redacted = redactSshSensitiveText(config('SSH_AUTH_SOCK'), text);
+ expect(redacted).toBe(
+ '<identity-agent> <identity-agent> <identity-file> <identity-file>',
+ );
+ });
+
+ it('redacts explicit Windows named pipes without depending on process.platform', () => {
+ const pipe = String.raw`\\.\pipe\openssh-ssh-agent`;
+ expect(redactSshSensitiveText(config(pipe), `connect ${pipe} failed`))
+ .toBe('connect <identity-agent> failed');
+ });
+
+ it('uses the default endpoint when IdentityAgent is absent', () => {
+ process.env.SSH_AUTH_SOCK = '/private/tmp/default-agent.sock';
+ const endpoint = previewAgentEndpoint(undefined).endpoint;
+ expect(endpoint).toBeTruthy();
+ expect(redactSshSensitiveText(config(), `connect ${endpoint} failed`))
+ .toBe('connect <identity-agent> failed');
+ });
+
+ it('does not replace the none sentinel or an unset variable with ordinary text', () => {
+ delete process.env.CINDY_TEST_UNSET_AGENT;
+ expect(redactSshSensitiveText(config('none'), 'none is an ordinary word'))
+ .toBe('none is an ordinary word');
+ expect(redactSshSensitiveText(
+ config('$CINDY_TEST_UNSET_AGENT'),
+ 'endpoint $CINDY_TEST_UNSET_AGENT unavailable',
+ )).toBe('endpoint <identity-agent> unavailable');
+ expect(redactSshSensitiveText(config('$CINDY_TEST_UNSET_AGENT'), 'ordinary text'))
+ .toBe('ordinary text');
+ expect(redactSshSensitiveText(config(''), 'ordinary text'))
+ .toBe('ordinary text');
+ });
+});
diff --git a/packages/maker-remote-ssh/src/credentials.ts b/packages/maker-remote-ssh/src/credentials.ts
index 402807cc06..5352c4a471 100644
--- a/packages/maker-remote-ssh/src/credentials.ts
+++ b/packages/maker-remote-ssh/src/credentials.ts
@@ -5,11 +5,11 @@
* 1. SSH agent, unfiltered (authMethod='agent', no identityFile)
* → enumerate every key in the agent. Risks tripping MaxAuthTries
* when the agent holds many keys; fine for users with 1-2.
- * 2. SSH agent, pinned to one key (authMethod='agent', identityFile=<pubkey>)
- * → wrap the agent in a FilteredAgent that only offers the matching
- * identity. Same UX as OpenSSH CLI's `IdentitiesOnly yes` + the
- * agent still owns the (cached) passphrase so the user doesn't
- * retype it. This is the recommended setup for multi-host devs.
+ * 2. SSH agent, pinned to an ordered key set
+ * → an explicit Cindy marker pin or effective `IdentitiesOnly yes`
+ * supplies public-key fingerprints. FilteredAgent offers only those
+ * identities, in SSH config order. The agent still owns any cached
+ * passphrases; Cindy never decrypts private keys for this path.
* 3. Identity file (authMethod='key', identityFile=<private key>)
* → read the file, hand the bytes straight to ssh2. Bypasses the
* agent entirely; encrypted keys need a passphrase per connect.
@@ -25,7 +25,12 @@
import { promises as fs } from 'node:fs';
import type { BaseAgent } from 'ssh2';
-import { createFilteredAgentFromPubkey } from './filteredAgent.js';
+import { createFilteredAgentFromFingerprints } from './filteredAgent.js';
+import {
+ resolveAgentEndpoint,
+ resolveIdentityFingerprints,
+ SSH_AGENT_UNAVAILABLE_CODE,
+} from './sshAuthentication.js';
import type { HostConfig } from './types.js';
/**
@@ -41,6 +46,8 @@ export const KEY_FILE_UNREADABLE_CODE = 'KEY_FILE_UNREADABLE';
/** 轮 21-W2 MEDIUM:agent + pinned-key 解析失败(缺 .pub/内容非法/不匹配)——
* 确定性本地配置错误, 不应落进 SSH_CONNECT_FAILED(可重试语义)。 */
export const PINNED_AGENT_FAILED_CODE = 'PINNED_AGENT_FAILED';
+/** Cindy can discover an SSH config it cannot faithfully express in ssh2. */
+export const SSH_CONFIG_AUTH_UNSUPPORTED_CODE = 'SSH_CONFIG_AUTH_UNSUPPORTED';
export interface ResolvedAuth {
/**
@@ -57,51 +64,66 @@ export interface ResolvedAuth {
label: string;
}
-/** Detect platform default SSH agent endpoint. */
-export function defaultAgentEndpoint(): string | undefined {
- if (process.platform === 'win32') {
- // OpenSSH agent (default-installed on Win10 1809+) exposes a named pipe.
- // ssh2 special-cases this path on win32; falls back to Pageant if needed.
- return '\\\\.\\pipe\\openssh-ssh-agent';
+export async function resolveAuth(host: HostConfig): Promise<ResolvedAuth> {
+ // Discovery may retain a host in the list while marking it unsupported so
+ // the UI can explain why Cindy cannot faithfully reproduce the SSH config.
+ // This guard must run before either auth branch; otherwise a marked key host
+ // could still connect to a default endpoint after Match directives were
+ // ignored.
+ if (host.sshAuthentication?.unsupportedReason) {
+ throwUnsupported(host.sshAuthentication.unsupportedReason);
}
- return process.env.SSH_AUTH_SOCK;
-}
-export async function resolveAuth(host: HostConfig): Promise<ResolvedAuth> {
if (host.authMethod === 'agent') {
- const endpoint = defaultAgentEndpoint();
- if (!endpoint) {
- throw new Error(
- process.platform === 'win32'
- ? 'OpenSSH agent named pipe not available. Start the "OpenSSH Authentication Agent" service.'
- : '$SSH_AUTH_SOCK is not set. Start ssh-agent and `ssh-add` your key first.',
- );
- }
- // Pinned-key flavour: identityFile present alongside agent auth → we
- // treat identityFile as a *public* key reference (path may point at the
- // private key, but the matching .pub sits next to it by convention).
- // Wrap the agent so only that fingerprint gets offered, bypassing the
- // MaxAuthTries-trigger of enumerating every loaded key.
- if (host.identityFile) {
- const pubkeyPath = host.identityFile.endsWith('.pub')
- ? host.identityFile
- : `${host.identityFile}.pub`;
- try {
- const filtered = await createFilteredAgentFromPubkey(pubkeyPath, endpoint);
- return { agent: filtered, label: `ssh-agent[${baseName(pubkeyPath)}]` };
- } catch (err) {
- // 轮 21-W2 MEDIUM:tag PINNED_AGENT_FAILED —— 本地配置错误(缺 .pub /
- // 内容非法 / 与 loaded key 不匹配), 不应落进 SSH_CONNECT_FAILED(可重试
- // 语义)。classifyConnectFailure 按稳定 code 分类, 不 pattern-match 文本。
+ let allowedFingerprints = host.sshAuthentication?.allowedAgentFingerprints;
+
+ // A marker-authenticated agent host may carry an explicit Cindy pin even
+ // when IdentitiesOnly is no. External IdentityFile metadata never enters
+ // HostConfig.identityFile, so it cannot accidentally become a pin.
+ if (!allowedFingerprints && host.identityFile) {
+ const resolved = await resolveIdentityFingerprints(host.identityFile);
+ allowedFingerprints = resolved.fingerprints;
+ if (allowedFingerprints.length === 0) {
const e = new Error(
- `agent + pinned key failed (${(err as Error).message}). ` +
- `Make sure ${pubkeyPath} exists and is a valid SSH public key, ` +
- `and that the matching private key is loaded in ssh-agent ('ssh-add ${pubkeyPath.replace(/\.pub$/, '')}').`,
+ `agent + pinned key failed: ${host.identityFile} is not a readable public key `
+ + `and its .pub sibling is unavailable or invalid`,
);
(e as { code?: string }).code = PINNED_AGENT_FAILED_CODE;
throw e;
}
}
+
+ // Validate deterministic configuration limits before touching the local
+ // Agent endpoint. This keeps a missing SSH_AUTH_SOCK from masking the
+ // more actionable IdentitiesOnly capability error (and makes the result
+ // independent of whether an Agent happens to be running in the process
+ // environment).
+ if (host.sshAuthentication?.identitiesOnly
+ && (!allowedFingerprints || allowedFingerprints.length === 0)) {
+ throwUnsupported('IdentitiesOnly yes has no public key Cindy can use to pin the agent');
+ }
+
+ let endpoint: string;
+ try {
+ endpoint = await resolveAgentEndpoint(host.sshAuthentication?.identityAgent);
+ } catch (err) {
+ if ((err as { code?: unknown } | null)?.code === SSH_AGENT_UNAVAILABLE_CODE) throw err;
+ throwUnsupported((err as Error).message);
+ }
+
+ if (allowedFingerprints && allowedFingerprints.length > 0) {
+ try {
+ const filtered = createFilteredAgentFromFingerprints(allowedFingerprints, endpoint);
+ return {
+ agent: filtered,
+ label: allowedFingerprints.length === 1
+ ? 'ssh-agent[filtered]'
+ : `ssh-agent[filtered:${allowedFingerprints.length}]`,
+ };
+ } catch (err) {
+ throwUnsupported((err as Error).message);
+ }
+ }
return { agent: endpoint, label: 'ssh-agent' };
}
@@ -134,6 +156,15 @@ export async function resolveAuth(host: HostConfig): Promise<ResolvedAuth> {
throw new Error(`unsupported authMethod: ${(host as { authMethod: string }).authMethod}`);
}
+function throwUnsupported(reason: string): never {
+ const error = new Error(
+ `SSH config authentication is outside Cindy's supported subset: ${reason}. `
+ + 'Terminal ssh may still work with this configuration.',
+ );
+ (error as { code?: string }).code = SSH_CONFIG_AUTH_UNSUPPORTED_CODE;
+ throw error;
+}
+
function baseName(p: string): string {
const i = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\'));
return i >= 0 ? p.slice(i + 1) : p;
diff --git a/packages/maker-remote-ssh/src/filteredAgent.ts b/packages/maker-remote-ssh/src/filteredAgent.ts
index 803e115a37..9118bfeec3 100644
--- a/packages/maker-remote-ssh/src/filteredAgent.ts
+++ b/packages/maker-remote-ssh/src/filteredAgent.ts
@@ -23,8 +23,7 @@
*/
import crypto from 'node:crypto';
-import { promises as fs } from 'node:fs';
-import { BaseAgent, createAgent, utils, type ParsedKey, type PublicKeyEntry, type SignCallback, type SigningRequestOptions } from 'ssh2';
+import { BaseAgent, createAgent, type ParsedKey, type PublicKeyEntry, type SignCallback, type SigningRequestOptions } from 'ssh2';
/** SHA256 base64 (without trailing `=` and without the `SHA256:` prefix). */
export function rawFingerprintOfPublicKey(blob: Buffer): string {
@@ -78,25 +77,34 @@ function asParsedKey(item: ParsedKey | PublicKeyEntry): ParsedKey | null {
*/
export class FilteredAgent extends BaseAgent<ParsedKey> {
private readonly upstream: BaseAgent<ParsedKey>;
- /** Full `SHA256:...` form. Compared verbatim against `sshFingerprint`. */
- private readonly allowedFingerprint: string;
+ /** Full `SHA256:...` forms, de-duplicated in OpenSSH configuration order. */
+ private readonly allowedFingerprints: string[];
- constructor(upstream: BaseAgent<ParsedKey>, allowedFingerprint: string) {
+ constructor(upstream: BaseAgent<ParsedKey>, allowedFingerprints: string | readonly string[]) {
super();
this.upstream = upstream;
- this.allowedFingerprint = allowedFingerprint;
+ const values = typeof allowedFingerprints === 'string'
+ ? [allowedFingerprints]
+ : [...allowedFingerprints];
+ this.allowedFingerprints = values.filter((value, index) => values.indexOf(value) === index);
+ if (this.allowedFingerprints.length === 0) {
+ throw new Error('FilteredAgent requires at least one allowed fingerprint');
+ }
}
getIdentities(cb: (err: Error | undefined, publicKeys?: ParsedKey[]) => void): void {
this.upstream.getIdentities((err, keys) => {
if (err) return cb(err);
- const matches: ParsedKey[] = [];
+ const byFingerprint = new Map<string, ParsedKey>();
for (const item of keys ?? []) {
const key = asParsedKey(item);
- if (key && sshFingerprint(key) === this.allowedFingerprint) {
- matches.push(key);
- }
+ if (key) byFingerprint.set(sshFingerprint(key), key);
}
+ // OpenSSH offers configured identities in configuration order. Agent
+ // enumeration order is unrelated and can hit MaxAuthTries first.
+ const matches = this.allowedFingerprints
+ .map((fingerprint) => byFingerprint.get(fingerprint))
+ .filter((key): key is ParsedKey => key !== undefined);
cb(undefined, matches);
});
}
@@ -118,29 +126,10 @@ export class FilteredAgent extends BaseAgent<ParsedKey> {
}
}
-/**
- * Build a `FilteredAgent` from a public-key file path. Reads the .pub,
- * extracts the SHA256 fingerprint, and wraps the platform-default agent
- * endpoint (UNIX socket on POSIX, OpenSSH named pipe on Windows).
- *
- * Throws on:
- * - pubkey file missing / unreadable
- * - malformed .pub content (parseKey failure)
- */
-export async function createFilteredAgentFromPubkey(
- pubkeyPath: string,
+export function createFilteredAgentFromFingerprints(
+ fingerprints: readonly string[],
agentEndpoint: string,
-): Promise<FilteredAgent> {
- const buf = await fs.readFile(pubkeyPath);
- const parsed = utils.parseKey(buf.toString('utf-8').trim());
- if (parsed instanceof Error) {
- throw new Error(`parse pubkey ${pubkeyPath} failed: ${parsed.message}`);
- }
- const key = Array.isArray(parsed) ? parsed[0] : parsed;
- if (!key) {
- throw new Error(`parse pubkey ${pubkeyPath} returned no key`);
- }
- const fingerprint = sshFingerprint(key);
+): FilteredAgent {
const upstream = createAgent(agentEndpoint) as BaseAgent<ParsedKey>;
- return new FilteredAgent(upstream, fingerprint);
+ return new FilteredAgent(upstream, fingerprints);
}
diff --git a/packages/maker-remote-ssh/src/hostKeys.ts b/packages/maker-remote-ssh/src/hostKeys.ts
index ee07366c01..5dba77b188 100644
--- a/packages/maker-remote-ssh/src/hostKeys.ts
+++ b/packages/maker-remote-ssh/src/hostKeys.ts
@@ -26,8 +26,12 @@ import path from 'node:path';
export interface HostKeyStore {
/** Trusted fingerprint for `key`, or null when the host is unknown. */
get(key: string): Promise<string | null>;
- /** Record (or overwrite) the trusted fingerprint for `key`. */
- set(key: string, fingerprint: string): Promise<void>;
+ /**
+ * Record the trusted fingerprint for `key`. `shouldCommit` is checked inside
+ * the serialized write slot so a cancelled SSH attempt cannot persist after
+ * it has become stale while waiting for another host-key write.
+ */
+ set(key: string, fingerprint: string, shouldCommit?: () => boolean): Promise<void>;
/**
* Discard any in-memory cache so the next `get` or `set` re-reads from
* the backing store. For in-memory stores this is a no-op.
@@ -105,7 +109,7 @@ export class FileHostKeyStore implements HostKeyStore {
}
}
- async set(key: string, fingerprint: string): Promise<void> {
+ async set(key: string, fingerprint: string, shouldCommit?: () => boolean): Promise<void> {
// Load inside the slot, not outside. If reload() is called between a
// caller's get() and their set() (post-load/pre-persist window), an
// outside-slot load returns a stale map reference and the conflict check
@@ -114,6 +118,7 @@ export class FileHostKeyStore implements HostKeyStore {
// permanently poison all subsequent writes.
const mySlot = this.writeChain.catch(() => {}).then(async () => {
const map = await this.load();
+ if (shouldCommit && !shouldCommit()) return;
if (map[key] === fingerprint) return; // concurrent winner already did our work
if (map[key] !== undefined) {
// A concurrent first-use already claimed this key with a different
diff --git a/packages/maker-remote-ssh/src/index.ts b/packages/maker-remote-ssh/src/index.ts
index 6897f40c19..b800ef3d60 100644
--- a/packages/maker-remote-ssh/src/index.ts
+++ b/packages/maker-remote-ssh/src/index.ts
@@ -1,7 +1,7 @@
/**
* @cindy/maker-remote-ssh — SSH remote host management for xdt-maker.
*
- * Phase A: connection lifecycle + ~/.ssh/config IO + credential resolution.
+ * Phase A: connection lifecycle + OpenSSH discovery/managed writes + credential resolution.
* Phase B (next): bootstrap agent CLI on remote + RemoteAgent that spawns
* claude/codex over an exec channel + session ingest.
*/
@@ -101,23 +101,51 @@ export {
export type { HostKeyStore, HostKeyDecision } from './hostKeys.js';
export {
+ addManagedHost,
+ addManagedHostWithInclude,
+ defaultManagedSshConfigPath,
defaultSshConfigPath,
+ ensureManagedConfigInclude,
readSshConfig,
+ readSshConfigDetailed,
+ removeManagedHost,
+ updateManagedHostFields,
upsertHost,
updateHostFields,
removeHost,
expandHome,
+ MANAGED_CONFIG_MARKER,
+ MANAGED_CONFIG_CONCURRENT_MODIFICATION_CODE,
+ MANAGED_CONFIG_OWNERSHIP_REQUIRED_CODE,
+ MANAGED_CONFIG_WRITE_TOKEN_REQUIRED_CODE,
+} from './sshConfig.js';
+export type {
+ ManagedHostAddReceipt,
+ ManagedConfigWriteToken,
+ ReadSshConfigOptions,
+ ReadSshConfigResult,
+ SshConfigDiagnostic,
} from './sshConfig.js';
export {
- defaultAgentEndpoint,
resolveAuth,
KEY_FILE_NOT_FOUND_CODE,
KEY_FILE_UNREADABLE_CODE,
PINNED_AGENT_FAILED_CODE,
+ SSH_CONFIG_AUTH_UNSUPPORTED_CODE,
} from './credentials.js';
export type { ResolvedAuth } from './credentials.js';
+export {
+ CINDY_DEFAULT_IDENTITY_NAMES,
+ defaultAgentEndpoint,
+ effectiveAuthenticationFingerprint,
+ previewAgentEndpoint,
+ resolveAgentEndpoint,
+ resolveIdentityFingerprints,
+ SSH_AGENT_UNAVAILABLE_CODE,
+} from './sshAuthentication.js';
+
export type {
AddHostInput,
AuthMethod,
@@ -125,4 +153,7 @@ export type {
HostSnapshot,
HostSource,
RemoteStatus,
+ SshAuthenticationMetadata,
} from './types.js';
+
+export { redactSshSensitiveText } from './sshRedaction.js';
diff --git a/packages/maker-remote-ssh/src/sshAuthentication.ts b/packages/maker-remote-ssh/src/sshAuthentication.ts
new file mode 100644
index 0000000000..ad53ae32f6
--- /dev/null
+++ b/packages/maker-remote-ssh/src/sshAuthentication.ts
@@ -0,0 +1,213 @@
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { utils } from 'ssh2';
+
+import { sshFingerprint } from './filteredAgent.js';
+import type { HostConfig } from './types.js';
+
+const MAX_PUBLIC_KEY_BYTES = 64 * 1024;
+
+/** The configured/default SSH Agent endpoint is not currently reachable. */
+export const SSH_AGENT_UNAVAILABLE_CODE = 'SSH_AGENT_UNAVAILABLE';
+
+/** Cindy's deliberately bounded default identity subset, not all OpenSSH versions. */
+export const CINDY_DEFAULT_IDENTITY_NAMES = [
+ 'id_rsa',
+ 'id_ecdsa',
+ 'id_ecdsa_sk',
+ 'id_ed25519',
+ 'id_ed25519_sk',
+] as const;
+
+export interface IdentityFingerprintResolution {
+ fingerprints: string[];
+ missing: boolean;
+ invalid: boolean;
+}
+
+/** Read only public-key-shaped text; never parse/decrypt a private-key body. */
+async function fingerprintPublicKeyFile(filePath: string): Promise<{
+ fingerprint?: string;
+ missing: boolean;
+ invalid: boolean;
+}> {
+ let handle: Awaited<ReturnType<typeof fs.open>>;
+ try {
+ handle = await fs.open(filePath, 'r');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ return { missing: true, invalid: false };
+ }
+ return { missing: false, invalid: true };
+ }
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_PUBLIC_KEY_BYTES) {
+ return { missing: false, invalid: true };
+ }
+ const buffer = Buffer.alloc(stat.size);
+ const { bytesRead } = await handle.read(buffer, 0, stat.size, 0);
+ const text = buffer.subarray(0, bytesRead).toString('utf8').trim();
+ // utils.parseKey also accepts private keys. Admit only the one-line
+ // OpenSSH public-key form so discovery never decrypts or interprets any
+ // private-key serialization (OpenSSH, PEM, PuTTY, or otherwise).
+ if (!/^(?:ssh-|ecdsa-|sk-)[^\s]+\s+[A-Za-z0-9+/=]+(?:\s|$)/.test(text)) {
+ return { missing: false, invalid: true };
+ }
+ const parsed = utils.parseKey(text);
+ if (parsed instanceof Error) return { missing: false, invalid: true };
+ const key = Array.isArray(parsed) ? parsed[0] : parsed;
+ if (!key) return { missing: false, invalid: true };
+ return { fingerprint: sshFingerprint(key), missing: false, invalid: false };
+ } catch {
+ return { missing: false, invalid: true };
+ } finally {
+ await handle.close().catch(() => undefined);
+ }
+}
+
+/**
+ * Resolve one OpenSSH IdentityFile entry using only the path itself or its
+ * conventional `${path}.pub` sibling. An already-public `.pub` path is never
+ * extended again, and Cindy intentionally does not guess custom names such as
+ * `lab.key -> lab.pub`.
+ */
+export async function resolveIdentityFingerprints(
+ identityPath: string,
+): Promise<IdentityFingerprintResolution> {
+ const candidates = identityPath.toLowerCase().endsWith('.pub')
+ ? [identityPath]
+ : [identityPath, `${identityPath}.pub`];
+ let anyPresent = false;
+ let anyInvalid = false;
+ for (const candidate of candidates) {
+ const result = await fingerprintPublicKeyFile(candidate);
+ if (!result.missing) anyPresent = true;
+ if (result.invalid) anyInvalid = true;
+ if (result.fingerprint) {
+ return { fingerprints: [result.fingerprint], missing: false, invalid: false };
+ }
+ }
+ return {
+ fingerprints: [],
+ missing: !anyPresent,
+ invalid: anyPresent && anyInvalid,
+ };
+}
+
+export function defaultIdentityPaths(): string[] {
+ return CINDY_DEFAULT_IDENTITY_NAMES.map((name) => path.join(os.homedir(), '.ssh', name));
+}
+
+export function defaultAgentEndpoint(): string | undefined {
+ if (process.platform === 'win32') return '\\\\.\\pipe\\openssh-ssh-agent';
+ return process.env.SSH_AUTH_SOCK;
+}
+
+function expandEnvironment(value: string): { value?: string; error?: string } {
+ let missing = false;
+ const expanded = value.replace(
+ /\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g,
+ (_match, braced: string | undefined, plain: string | undefined) => {
+ const name = braced ?? plain!;
+ const replacement = process.env[name];
+ if (replacement === undefined) {
+ missing = true;
+ return '';
+ }
+ return replacement;
+ },
+ );
+ return missing
+ ? { error: 'the configured IdentityAgent environment variable is not set' }
+ : { value: expanded };
+}
+
+export function previewAgentEndpoint(identityAgent?: string): {
+ endpoint?: string;
+ unsupportedReason?: string;
+ unavailableReason?: string;
+ explicit: boolean;
+} {
+ if (identityAgent === undefined) {
+ return { endpoint: defaultAgentEndpoint(), explicit: false };
+ }
+ if (identityAgent === 'none') {
+ return {
+ unsupportedReason: 'IdentityAgent none disables SSH Agent authentication',
+ explicit: true,
+ };
+ }
+ if (identityAgent.includes('%')) {
+ return {
+ unsupportedReason: 'Cindy does not support percent-token expansion in IdentityAgent',
+ explicit: true,
+ };
+ }
+ const source = identityAgent === 'SSH_AUTH_SOCK' ? '$SSH_AUTH_SOCK' : identityAgent;
+ const expanded = expandEnvironment(source);
+ if (expanded.error) return { unavailableReason: expanded.error, explicit: true };
+ let endpoint = expanded.value!;
+ if (endpoint === '~') endpoint = os.homedir();
+ else if (endpoint.startsWith('~/') || endpoint.startsWith('~\\')) {
+ endpoint = path.join(os.homedir(), endpoint.slice(2).replace(/\\/g, '/'));
+ }
+ if (!endpoint) {
+ return { unavailableReason: 'the configured IdentityAgent endpoint is empty', explicit: true };
+ }
+ return { endpoint, explicit: true };
+}
+
+function throwAgentUnavailable(reason: string): never {
+ const error = new Error(reason);
+ (error as { code?: string }).code = SSH_AGENT_UNAVAILABLE_CODE;
+ throw error;
+}
+
+export async function resolveAgentEndpoint(identityAgent?: string): Promise<string> {
+ const preview = previewAgentEndpoint(identityAgent);
+ if (preview.unsupportedReason) throw new Error(preview.unsupportedReason);
+ if (preview.unavailableReason) throwAgentUnavailable(preview.unavailableReason);
+ if (!preview.endpoint) {
+ throwAgentUnavailable(
+ process.platform === 'win32'
+ ? 'OpenSSH agent named pipe not available. Start the "OpenSSH Authentication Agent" service.'
+ : '$SSH_AUTH_SOCK is not set. Start ssh-agent and `ssh-add` your key first.',
+ );
+ }
+ if (preview.explicit && process.platform !== 'win32') {
+ try {
+ const stat = await fs.stat(preview.endpoint);
+ if (!stat.isSocket()) throw new Error('not a socket');
+ } catch {
+ throwAgentUnavailable('the configured IdentityAgent endpoint is unavailable');
+ }
+ }
+ return preview.endpoint;
+}
+
+/** Stable comparison key shared by main connections and Agent Proxy tunnels. */
+export function effectiveAuthenticationFingerprint(host: HostConfig): string {
+ if (host.authMethod === 'key') {
+ return JSON.stringify({
+ method: 'key',
+ identityFile: host.identityFile ?? null,
+ unsupportedReason: host.sshAuthentication?.unsupportedReason ?? null,
+ });
+ }
+ const metadata = host.sshAuthentication;
+ const endpoint = previewAgentEndpoint(metadata?.identityAgent);
+ return JSON.stringify({
+ method: 'agent',
+ marker: metadata?.marker ?? null,
+ explicitPin: host.identityFile ?? null,
+ identitiesOnly: metadata?.identitiesOnly ?? false,
+ endpoint: endpoint.endpoint ?? null,
+ endpointUnsupported: endpoint.unsupportedReason ?? null,
+ endpointUnavailable: endpoint.unavailableReason ?? null,
+ configuredIdentityFiles: metadata?.configuredIdentityFiles ?? [],
+ allowedAgentFingerprints: metadata?.allowedAgentFingerprints ?? null,
+ unsupportedReason: metadata?.unsupportedReason ?? null,
+ });
+}
diff --git a/packages/maker-remote-ssh/src/sshConfig.ts b/packages/maker-remote-ssh/src/sshConfig.ts
index ea41a7aec5..8cc62339a5 100644
--- a/packages/maker-remote-ssh/src/sshConfig.ts
+++ b/packages/maker-remote-ssh/src/sshConfig.ts
@@ -1,47 +1,143 @@
/**
- * SSH config IO — read/write ~/.ssh/config in OpenSSH format.
+ * OpenSSH config discovery plus Cindy's narrowly-owned config writer.
*
- * Phase A surface:
- * - readSshConfig(): list every concrete host (skipping wildcards
- * like `Host *` or `Host foo*`).
- * - upsertHost(): add or replace one host block. Preserves all
- * other entries verbatim.
- * - removeHost(): drop one host block. No-op if absent.
- *
- * We intentionally do NOT inherit / merge wildcard rules in readSshConfig
- * — the renderer wants concrete hosts to display; `ssh` itself will apply
- * wildcards when we eventually exec it. Concrete-host enumeration is the
- * "user-facing" set.
+ * Discovery intentionally implements only the subset Cindy consumes. Include
+ * is expanded at root scope and inside a pure `Host *` block. Other Host
+ * scopes are conditional, so expanding them without evaluating OpenSSH's full
+ * matcher would invent aliases that `ssh <alias>` cannot actually see. If a
+ * skipped conditional Include or an unevaluated Match may affect a discovered
+ * alias, that host remains visible but is marked unsupported instead of using
+ * default fields.
*/
+import { createHash, randomBytes } from 'node:crypto';
import { promises as fs } from 'node:fs';
-import path from 'node:path';
import os from 'node:os';
+import path from 'node:path';
import SSHConfig from 'ssh-config';
+import {
+ defaultIdentityPaths,
+ resolveIdentityFingerprints,
+ type IdentityFingerprintResolution,
+} from './sshAuthentication.js';
import type { HostConfig } from './types.js';
const DEFAULT_PORT = 22;
+const MAX_INCLUDE_DEPTH = 16;
+const MAX_INCLUDE_FILES = 64;
+const MAX_INCLUDE_BYTES = 1024 * 1024;
+const AUTH_MARKER_PREFIX = '# xdt-maker:auth=';
+/** File-level marker proving that Cindy created/owns the managed config. */
+export const MANAGED_CONFIG_MARKER = '# xdt-maker:managed=v1';
+export const MANAGED_CONFIG_OWNERSHIP_REQUIRED_CODE = 'SSH_CONFIG_OWNERSHIP_REQUIRED';
+export const MANAGED_CONFIG_CONCURRENT_MODIFICATION_CODE = 'SSH_CONFIG_CONCURRENT_MODIFICATION';
+export const MANAGED_CONFIG_WRITE_TOKEN_REQUIRED_CODE = 'SSH_CONFIG_WRITE_TOKEN_REQUIRED';
+const MATCH_NO_ARGUMENT_CRITERIA = new Set(['all', 'canonical', 'final']);
+const MATCH_ONE_ARGUMENT_CRITERIA = new Set([
+ 'command',
+ 'exec',
+ 'host',
+ 'localaddress',
+ 'localcommand',
+ 'localnetwork',
+ 'localport',
+ 'localuser',
+ 'originalhost',
+ 'remoteaddress',
+ 'remoteport',
+ 'tagged',
+ 'user',
+ 'version',
+]);
-/** Resolve `~/.ssh/config` on the current OS. */
-export function defaultSshConfigPath(): string {
- return path.join(os.homedir(), '.ssh', 'config');
+export interface SshConfigDiagnostic {
+ path: string;
+ kind: 'io' | 'syntax' | 'limit';
+ message: string;
+ recoveryHint: string;
+}
+
+export interface ReadSshConfigOptions {
+ /** Cindy-owned config file. Omit it to make every discovered host read-only. */
+ managedConfigPath?: string;
+}
+
+export interface ReadSshConfigResult {
+ hosts: HostConfig[];
+ diagnostic: SshConfigDiagnostic | null;
+ warnings: string[];
+ /**
+ * Opaque SHA-256 token for the exact Cindy-owned managed config bytes read
+ * during this discovery pass. Trusted hosts may pass it to managed writers;
+ * it must never be projected over IPC or stored on a host snapshot.
+ * Undefined when no managed path was requested, the file was not reached,
+ * or its Cindy ownership marker was absent.
+ */
+ managedConfigWriteToken?: ManagedConfigWriteToken;
}
+declare const managedConfigWriteTokenBrand: unique symbol;
+export type ManagedConfigWriteToken = string & {
+ readonly [managedConfigWriteTokenBrand]: true;
+};
+
/**
- * Expand a leading `~` (or `~/`, `~\`) to the user's home directory.
- *
- * Exported so the ADD/UPDATE IPC boundary can normalize `identityFile` the
- * same way the config-read path does — Node never expands `~`, so a literal
- * `~/.ssh/...` stored in the pool host config would fail `fs.readFile` /
- * ssh-add. The `~\` prefix normalizes backslashes to `/` (a no-op on Windows,
- * but required on POSIX where backslash is a filename character).
+ * Conditional rollback for a host that was successfully published to the
+ * managed SSH file. The rollback refuses to overwrite later external edits.
*/
-export function expandHome(p: string): string {
- if (p === '~') return os.homedir();
- if (p.startsWith('~/')) return path.join(os.homedir(), p.slice(2));
- if (p.startsWith('~\\')) return path.join(os.homedir(), p.slice(2).replace(/\\/g, '/'));
- return p;
+export interface ManagedHostAddReceipt {
+ rollback(): Promise<boolean>;
+}
+
+type AuthMarker = 'agent' | 'key';
+type Scope =
+ | { kind: 'root' }
+ | { kind: 'host'; declaration: HostDeclaration }
+ | { kind: 'match'; declaration: MatchDeclaration };
+
+interface HostDeclaration {
+ patterns: string[];
+ sourcePath: string;
+ physicalPath: string;
+ marker: AuthMarker | null;
+ order: number;
+}
+
+interface MatchDeclaration {
+ expression: string;
+ /** True once the block contains a directive Cindy would otherwise ignore. */
+ hasDirectives: boolean;
+ order: number;
+}
+
+interface SkippedConditionalInclude {
+ /** Host scope whose effective directives may come from the skipped Include. */
+ scope: Extract<Scope, { kind: 'host' }>;
+}
+
+interface DirectiveRecord {
+ name: string;
+ value: string;
+ scope: Scope;
+ order: number;
+}
+
+interface WalkState {
+ rootDir: string;
+ managedComparable: string | null;
+ visited: Set<string>;
+ files: string[];
+ bytes: number;
+ declarations: HostDeclaration[];
+ matches: MatchDeclaration[];
+ skippedConditionalIncludes: SkippedConditionalInclude[];
+ incompleteUnconditionalInclude: boolean;
+ managedConfigOwned: boolean;
+ managedConfigWriteToken?: ManagedConfigWriteToken;
+ directives: DirectiveRecord[];
+ warnings: string[];
+ order: number;
}
interface SshConfigSection {
@@ -49,368 +145,1485 @@ interface SshConfigSection {
before?: string;
after?: string;
param?: string;
- /**
- * Separator between key and value as the ssh-config serializer expects it
- * (normally a single space). MUST be set on directive nodes we synthesize —
- * omitting it makes `toString()` emit `KeyundefinedValue` and corrupts the
- * file. See applyDirective insert path.
- */
separator?: string;
- value?: string | string[];
- /** Present on comment nodes (type=2). */
+ quoted?: boolean;
+ value?: string | SshConfigValueToken | Array<string | SshConfigValueToken>;
content?: string;
config?: SshConfigSection[];
}
-/** ssh-config AST: type=1 = directive, type=2 = comment, type=3 = blank line. */
+interface SshConfigValueToken { val?: unknown }
+
const SSH_CONFIG_DIRECTIVE_TYPE = 1;
const SSH_CONFIG_COMMENT_TYPE = 2;
-/**
- * Marker comment inside a host block that records the user's auth-method
- * choice. Needed because both 'agent + pinned key' and 'key' modes write
- * the same `IdentityFile + IdentitiesOnly yes` directives — we'd lose the
- * distinction on re-read otherwise.
- *
- * Reads as plain `#` comment to OpenSSH (ignored). Absence of the marker
- * with an IdentityFile present means "legacy key-file host" — we preserve
- * that interpretation for backward compat with hosts added before this
- * marker was introduced.
- */
-const AUTH_MARKER_PREFIX = '# xdt-maker:auth=';
+export function defaultSshConfigPath(): string {
+ return path.join(os.homedir(), '.ssh', 'config');
+}
+
+export function defaultManagedSshConfigPath(): string {
+ return path.join(os.homedir(), '.ssh', 'cindy.conf');
+}
-function readAuthMarker(section: SshConfigSection): 'agent' | 'key' | null {
- for (const child of section.config ?? []) {
- if (child.type !== SSH_CONFIG_COMMENT_TYPE) continue;
- const content = (child.content ?? '').trim();
- if (content === `${AUTH_MARKER_PREFIX}agent`) return 'agent';
- if (content === `${AUTH_MARKER_PREFIX}key`) return 'key';
+export function expandHome(value: string): string {
+ if (value === '~') return os.homedir();
+ if (value.startsWith('~/')) return path.join(os.homedir(), value.slice(2));
+ if (value.startsWith('~\\')) {
+ return path.join(os.homedir(), value.slice(2).replace(/\\/g, '/'));
}
- return null;
+ return value;
}
-function isHostDirective(section: SshConfigSection): boolean {
- return section.param?.toLowerCase() === 'host';
+type IncludePathExpansionResult =
+ | { pattern: string; warning?: never }
+ | { pattern?: never; warning: string };
+
+/** Expand the environment and home-directory forms accepted by OpenSSH Include. */
+function expandIncludePath(value: string): IncludePathExpansionResult {
+ let pattern = '';
+ let cursor = 0;
+ while (cursor < value.length) {
+ const start = value.indexOf('${', cursor);
+ if (start < 0) {
+ pattern += value.slice(cursor);
+ break;
+ }
+ pattern += value.slice(cursor, start);
+ const end = value.indexOf('}', start + 2);
+ if (end < 0) {
+ return { warning: 'malformed environment variable expression; Include was not expanded.' };
+ }
+ const name = value.slice(start + 2, end);
+ if (!name || name.includes('{')) {
+ return { warning: 'malformed environment variable expression; Include was not expanded.' };
+ }
+ const environmentValue = process.env[name];
+ if (environmentValue === undefined) {
+ return {
+ warning: `environment variable "${name}" is not set; Include was not expanded.`,
+ };
+ }
+ pattern += environmentValue;
+ cursor = end + 1;
+ }
+
+ const currentUserPattern = /^~([^/\\]+)(?:[/\\](.*))?$/.exec(pattern);
+ if (currentUserPattern) {
+ const username = currentUserPattern[1]!;
+ if (username !== os.userInfo().username) {
+ return {
+ warning: `home directory for user "${username}" cannot be resolved by Cindy; Include was not expanded.`,
+ };
+ }
+ const remainder = currentUserPattern[2];
+ return {
+ pattern: remainder === undefined
+ ? os.homedir()
+ : path.join(os.homedir(), remainder.replace(/\\/g, '/')),
+ };
+ }
+
+ return { pattern: expandHome(pattern) };
}
-/**
- * Read and parse ~/.ssh/config (or any path). Returns a list of concrete
- * hosts — wildcards and `Match` blocks are skipped. Missing file → [].
- */
-export async function readSshConfig(filePath = defaultSshConfigPath()): Promise<HostConfig[]> {
- let raw: string;
+type HostNameExpansionResult =
+ | { hostname: string; unsupportedToken?: never }
+ | { hostname?: never; unsupportedToken: string };
+
+/** HostName accepts only %% and %h; expand once so alias contents are not re-read as tokens. */
+function expandHostNameTokens(value: string, alias: string): HostNameExpansionResult {
+ let hostname = '';
+ for (let index = 0; index < value.length; index += 1) {
+ const char = value[index]!;
+ if (char !== '%') {
+ hostname += char;
+ continue;
+ }
+
+ const token = value[index + 1];
+ if (token === '%') hostname += '%';
+ else if (token === 'h') hostname += alias;
+ else return { unsupportedToken: token === undefined ? '%' : `%${token}` };
+ index += 1;
+ }
+ return { hostname };
+}
+
+export async function readSshConfig(
+ filePath = defaultSshConfigPath(),
+ options: ReadSshConfigOptions = {},
+): Promise<HostConfig[]> {
+ const result = await readSshConfigDetailed(filePath, options);
+ if (result.diagnostic) throw new Error(result.diagnostic.message);
+ return result.hosts;
+}
+
+export async function readSshConfigDetailed(
+ filePath = defaultSshConfigPath(),
+ options: ReadSshConfigOptions = {},
+): Promise<ReadSshConfigResult> {
+ const absoluteMainPath = path.resolve(filePath);
+ const managedComparable = options.managedConfigPath
+ ? await comparablePath(options.managedConfigPath)
+ : null;
+ const state: WalkState = {
+ rootDir: path.dirname(absoluteMainPath),
+ managedComparable,
+ visited: new Set(),
+ files: [],
+ bytes: 0,
+ declarations: [],
+ matches: [],
+ skippedConditionalIncludes: [],
+ incompleteUnconditionalInclude: false,
+ managedConfigOwned: false,
+ directives: [],
+ warnings: [],
+ order: 0,
+ };
+
try {
- raw = await fs.readFile(filePath, 'utf8');
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];
- throw err;
+ await walkFile(absoluteMainPath, { kind: 'root' }, state, 0, false);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ const warnings = options.managedConfigPath && await pathExists(options.managedConfigPath)
+ ? ['Cindy\'s SSH host file exists but is not reachable through a supported Include.']
+ : [];
+ return { hosts: [], diagnostic: null, warnings };
+ }
+ return {
+ hosts: [],
+ diagnostic: toConfigDiagnostic(absoluteMainPath, error),
+ warnings: state.warnings,
+ };
}
- const parsed = SSHConfig.parse(raw) as SshConfigSection[];
- const hosts: HostConfig[] = [];
+ if (options.managedConfigPath) {
+ const managedExists = await pathExists(options.managedConfigPath);
+ const reachedManaged = managedComparable
+ ? Array.from(state.visited).some((item) => pathsEqual(item, managedComparable))
+ : false;
+ if (managedExists && !reachedManaged) {
+ state.warnings.push('Cindy\'s SSH host file exists but is not reachable through a supported Include.');
+ }
+ }
+
+ return {
+ hosts: await buildHosts(state, managedComparable),
+ diagnostic: null,
+ warnings: state.warnings,
+ ...(state.managedConfigWriteToken
+ ? { managedConfigWriteToken: state.managedConfigWriteToken }
+ : {}),
+ };
+}
+
+async function walkFile(
+ filePath: string,
+ inheritedScope: Scope,
+ state: WalkState,
+ depth: number,
+ optional: boolean,
+): Promise<void> {
+ if (depth > MAX_INCLUDE_DEPTH) {
+ throw limitError(filePath, `Include nesting exceeds ${MAX_INCLUDE_DEPTH} levels`);
+ }
+
+ let physicalPath: string;
+ try {
+ physicalPath = await comparablePath(filePath);
+ } catch (error) {
+ if (optional && (error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw error;
+ }
+ if (state.visited.has(physicalPath)) return;
+
+ let rawBytes: Buffer;
+ try {
+ rawBytes = await fs.readFile(physicalPath);
+ } catch (error) {
+ if (optional && (error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw error;
+ }
+ if (state.files.length >= MAX_INCLUDE_FILES) {
+ throw limitError(physicalPath, `Include file count exceeds ${MAX_INCLUDE_FILES}`);
+ }
+ const bytes = rawBytes.byteLength;
+ if (state.bytes + bytes > MAX_INCLUDE_BYTES) {
+ throw limitError(physicalPath, `expanded SSH config exceeds ${MAX_INCLUDE_BYTES} bytes`);
+ }
+
+ const raw = rawBytes.toString('utf8');
+ try {
+ SSHConfig.parse(raw);
+ } catch (error) {
+ const syntaxError = new Error(
+ `failed to parse SSH config: ${error instanceof Error ? error.message : String(error)}`,
+ ) as Error & { code?: string; path?: string };
+ syntaxError.code = 'SSH_CONFIG_SYNTAX';
+ syntaxError.path = physicalPath;
+ throw syntaxError;
+ }
+
+ state.visited.add(physicalPath);
+ state.files.push(physicalPath);
+ state.bytes += bytes;
+ if (state.managedComparable !== null && pathsEqual(physicalPath, state.managedComparable)) {
+ state.managedConfigOwned = hasManagedConfigMarker(raw);
+ state.managedConfigWriteToken = state.managedConfigOwned
+ ? managedConfigToken(rawBytes)
+ : undefined;
+ }
+
+ let scope = inheritedScope;
+ const lines = raw.split(/\r?\n/);
+ for (let index = 0; index < lines.length; index += 1) {
+ const line = lines[index] ?? '';
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+
+ if (trimmed.startsWith('#')) {
+ if (scope.kind === 'host' && scope.declaration.marker === null) {
+ const marker = parseAuthMarker(trimmed);
+ if (marker) scope.declaration.marker = marker;
+ }
+ continue;
+ }
- for (const section of parsed) {
- if (!isHostDirective(section)) continue;
- const aliases = Array.isArray(section.value) ? section.value : [section.value];
- for (const aliasRaw of aliases) {
- if (typeof aliasRaw !== 'string') continue;
- const alias = aliasRaw.trim();
- if (!alias || alias.includes('*') || alias.includes('?') || alias.startsWith('!')) continue;
-
- // Pluck params out of this Host block (case-insensitive per spec).
- const params = new Map<string, string>();
- for (const child of section.config ?? []) {
- if (!child.param || typeof child.value !== 'string') continue;
- params.set(child.param.toLowerCase(), child.value);
+ const directive = parseDirectiveLine(trimmed);
+ if (!directive) continue;
+ const location = `${physicalPath}:${index + 1}`;
+
+ if (directive.keyword === 'host') {
+ const patterns = splitWords(directive.value);
+ const declaration: HostDeclaration = {
+ patterns,
+ sourcePath: filePath,
+ physicalPath,
+ marker: null,
+ order: state.order++,
+ };
+ state.declarations.push(declaration);
+ scope = { kind: 'host', declaration };
+ continue;
+ }
+
+ if (directive.keyword === 'match') {
+ const declaration: MatchDeclaration = {
+ expression: directive.value,
+ hasDirectives: false,
+ order: state.order++,
+ };
+ state.matches.push(declaration);
+ scope = { kind: 'match', declaration };
+ state.warnings.push(`${location}: Match is not evaluated by Cindy.`);
+ continue;
+ }
+
+ if (scope.kind === 'match') scope.declaration.hasDirectives = true;
+
+ if (directive.keyword === 'include') {
+ if (!isSupportedIncludeScope(scope)) {
+ if (scope.kind === 'host') {
+ state.skippedConditionalIncludes.push({ scope });
+ }
+ state.warnings.push(`${location}: conditional Include was not expanded.`);
+ continue;
}
+ for (const patternValue of splitWords(directive.value)) {
+ const expansion = expandIncludePath(patternValue);
+ if ('warning' in expansion) {
+ state.warnings.push(`${location}: ${expansion.warning}`);
+ state.incompleteUnconditionalInclude = true;
+ continue;
+ }
+ const expanded = expansion.pattern;
+ const absolutePattern = path.isAbsolute(expanded)
+ ? expanded
+ : path.resolve(state.rootDir, expanded);
+ for (const includedPath of await globPaths(absolutePattern)) {
+ const includedComparable = await comparablePath(includedPath);
+ const repeatedManagedGlob = hasGlob(expanded)
+ && state.managedComparable !== null
+ && state.visited.has(includedComparable)
+ && pathsEqual(includedComparable, state.managedComparable);
+ // The child starts in the parent's active scope. This local scope is
+ // deliberately restored when the recursive call returns.
+ await walkFile(includedPath, scope, state, depth + 1, true);
+ if (repeatedManagedGlob) {
+ state.warnings.push(
+ `${location}: Include glob reaches Cindy's SSH host file after it was already loaded.`,
+ );
+ }
+ }
+ }
+ continue;
+ }
+
+ if (isCanonicalizationDirective(directive.keyword)) {
+ state.warnings.push(`${location}: hostname canonicalization is not evaluated by Cindy.`);
+ if (directive.keyword === 'canonicalizehostname' && scope.kind !== 'match') {
+ state.directives.push({
+ name: directive.keyword,
+ value: firstWordOrRaw(directive.value),
+ scope,
+ order: state.order++,
+ });
+ }
+ continue;
+ }
+ if (scope.kind === 'match') continue;
- const identityFile = params.get('identityfile');
- // Auth-method rules:
- // IdentityFile absent → 'agent' (unfiltered, no key pin)
- // IdentityFile present + marker says agent → 'agent' + pinned key
- // IdentityFile present + marker says key → 'key'
- // IdentityFile present + no marker → 'key' (legacy host, backward compat)
- const marker = readAuthMarker(section);
- const authMethod: 'agent' | 'key' = identityFile
- ? (marker === 'agent' ? 'agent' : 'key')
- : 'agent';
- hosts.push({
- id: alias,
- hostname: params.get('hostname') ?? alias,
- port: parseIntSafe(params.get('port'), DEFAULT_PORT),
- user: params.get('user') ?? os.userInfo().username,
- authMethod,
- identityFile: identityFile ? expandHome(identityFile) : undefined,
- source: 'ssh-config',
+ const name = directive.keyword;
+ if (name === 'hostname'
+ || name === 'user'
+ || name === 'port'
+ || name === 'identityfile'
+ || name === 'identitiesonly'
+ || name === 'identityagent'
+ || name === 'hostkeyalias'
+ || name === 'proxyjump'
+ || name === 'proxycommand'
+ || name === 'certificatefile'
+ || name === 'pkcs11provider'
+ || name === 'securitykeyprovider') {
+ state.directives.push({
+ name,
+ value: firstWordOrRaw(directive.value),
+ scope,
+ order: state.order++,
});
}
}
+}
+async function buildHosts(
+ state: WalkState,
+ managedComparable: string | null,
+): Promise<HostConfig[]> {
+ const aliases: string[] = [];
+ const fingerprintCache = new Map<string, Promise<IdentityFingerprintResolution>>();
+ const seen = new Set<string>();
+ for (const declaration of state.declarations) {
+ for (const pattern of declaration.patterns) {
+ if (!isConcreteAlias(pattern) || seen.has(pattern)) continue;
+ seen.add(pattern);
+ aliases.push(pattern);
+ }
+ }
+
+ const hosts: HostConfig[] = [];
+ // Keep public-key inspection sequential. A config may contain many aliases
+ // pointing at the same identities; unbounded Promise.all would turn a small
+ // config into a burst of file descriptors during startup.
+ for (const alias of aliases) {
+ const introducing = state.declarations.filter((declaration) =>
+ declaration.patterns.some((pattern) => pattern === alias));
+ const firstIntroducing = introducing[0];
+ const identityDirectives = matchingDirectives(state.directives, alias, 'identityfile');
+ const introducingIdentity = identityDirectives.find((directive) =>
+ directive.scope.kind === 'host'
+ && directive.scope.declaration === firstIntroducing
+ && directive.value.toLowerCase() !== 'none')?.value;
+ const marker = firstIntroducing?.marker ?? null;
+ const matchMayAffectHost = state.matches.some((declaration) =>
+ declaration.hasDirectives
+ && matchExpressionMayApplyToAlias(declaration.expression, alias));
+ const conditionalIncludeMayAffectHost = state.skippedConditionalIncludes.some(
+ ({ scope }) => scopeMatches(scope, alias),
+ );
+ // Strategy B: ordinary OpenSSH hosts are Agent-first, independently of
+ // whether the concrete IdentityFile lives in the main file or an Include.
+ // Only Cindy's marker opts into direct private-key reads or an explicit
+ // agent pin. Compatibility trade-off: a legacy no-marker host that relied
+ // on Cindy reading an unencrypted private key must load it with ssh-add or
+ // migrate to a marked Cindy-managed key host. managedByCindy remains
+ // ownership-only.
+ const authMethod = marker ?? 'agent';
+ const identityRaw = marker === 'key'
+ ? introducingIdentity
+ : marker === 'agent'
+ ? introducingIdentity
+ : undefined;
+ const hostnameRaw = firstMatchingDirective(state.directives, alias, 'hostname');
+ const hostnameExpansion = hostnameRaw === undefined
+ ? { hostname: alias }
+ : expandHostNameTokens(hostnameRaw, alias);
+ const unsupportedHostNameToken = hostnameExpansion.unsupportedToken;
+ if (hostnameExpansion.unsupportedToken !== undefined) {
+ state.warnings.push(
+ `SSH host ${JSON.stringify(alias)} remains listed but unsupported because HostName uses token `
+ + `${JSON.stringify(hostnameExpansion.unsupportedToken)}.`,
+ );
+ }
+ // The alias is display-only on this path. unsupportedReason below prevents
+ // it from reaching TCP, TOFU, or endpoint fingerprinting.
+ const hostname = hostnameExpansion.hostname ?? alias;
+ const user = firstMatchingDirective(state.directives, alias, 'user')
+ ?? os.userInfo().username;
+ const port = parseIntSafe(firstMatchingDirective(state.directives, alias, 'port'), DEFAULT_PORT);
+
+ const uniquelyManaged = managedComparable !== null
+ && introducing.length === 1
+ && firstIntroducing?.patterns.length === 1
+ && pathsEqual(firstIntroducing.physicalPath, managedComparable);
+ const managedOwnership = uniquelyManaged && state.managedConfigOwned;
+
+ const identityFileDirectiveSeen = identityDirectives.length > 0;
+ const identityFileNoneSeen = identityDirectives.some(
+ (directive) => directive.value.toLowerCase() === 'none',
+ );
+ const identityContext: IdentityFileTokenContext = {
+ alias,
+ hostname,
+ user,
+ port,
+ hostKeyAlias: firstMatchingDirective(state.directives, alias, 'hostkeyalias'),
+ proxyJump: firstMatchingDirective(state.directives, alias, 'proxyjump'),
+ };
+ const concreteIdentityDirectives = identityDirectives
+ .filter((directive) => directive.value.toLowerCase() !== 'none');
+ const explicitIdentityFiles: string[] = [];
+ let unsupportedIdentityToken: string | undefined;
+ for (const directive of concreteIdentityDirectives) {
+ const expansion = expandIdentityFile(directive.value, identityContext);
+ if ('unsupportedToken' in expansion) {
+ unsupportedIdentityToken = expansion.unsupportedToken;
+ break;
+ }
+ explicitIdentityFiles.push(expansion.filePath);
+ }
+ if (unsupportedIdentityToken !== undefined) {
+ state.warnings.push(
+ `SSH host ${JSON.stringify(alias)} remains listed but unsupported because IdentityFile uses token `
+ + `${JSON.stringify(unsupportedIdentityToken)}.`,
+ );
+ }
+ const introducingIdentityIndex = identityRaw === undefined
+ ? -1
+ : concreteIdentityDirectives.findIndex((directive) => directive.value === identityRaw);
+ const identityFile = introducingIdentityIndex >= 0
+ ? explicitIdentityFiles[introducingIdentityIndex]
+ : undefined;
+ const identitiesOnlyRaw = firstMatchingDirective(
+ state.directives,
+ alias,
+ 'identitiesonly',
+ );
+ const identitiesOnly = identitiesOnlyRaw?.toLowerCase() === 'yes';
+ const configuredIdentityFiles = identityFileDirectiveSeen
+ ? explicitIdentityFiles
+ : identitiesOnly
+ ? defaultIdentityPaths()
+ : [];
+ const canonicalizeHostname = firstMatchingDirective(
+ state.directives,
+ alias,
+ 'canonicalizehostname',
+ )?.toLowerCase();
+ let unsupportedReason = state.incompleteUnconditionalInclude
+ ? 'Cindy could not completely expand an unconditional Include'
+ : matchMayAffectHost
+ ? 'Cindy does not evaluate a Match block that may affect this SSH host'
+ : conditionalIncludeMayAffectHost
+ ? 'Cindy does not expand a conditional Include that may affect this SSH host'
+ : canonicalizeHostname !== undefined && canonicalizeHostname !== 'no'
+ ? canonicalizeHostname === 'yes' || canonicalizeHostname === 'always'
+ ? 'Cindy does not implement OpenSSH hostname canonicalization'
+ : `unsupported CanonicalizeHostname value: ${canonicalizeHostname}`
+ : unsupportedHostNameToken !== undefined
+ ? `unsupported HostName token: ${unsupportedHostNameToken}`
+ : unsupportedIdentityToken !== undefined
+ ? `unsupported IdentityFile token: ${unsupportedIdentityToken}`
+ : identitiesOnlyRaw !== undefined
+ && identitiesOnlyRaw.toLowerCase() !== 'yes'
+ && identitiesOnlyRaw.toLowerCase() !== 'no'
+ ? `unsupported IdentitiesOnly value: ${identitiesOnlyRaw}`
+ : undefined;
+ const unsupportedTransportDirectives = ['proxyjump', 'proxycommand']
+ .filter((name) => {
+ const value = firstMatchingDirective(state.directives, alias, name);
+ return value !== undefined && value.toLowerCase() !== 'none';
+ });
+ if (unsupportedTransportDirectives.length > 0) {
+ unsupportedReason ??= `Cindy does not support ${unsupportedTransportDirectives.join(' / ')} transport configuration`;
+ }
+ const unsupportedAgentDirectives = [
+ 'certificatefile',
+ 'pkcs11provider',
+ 'securitykeyprovider',
+ ].filter((name) => matchingDirectives(state.directives, alias, name).length > 0);
+ if (authMethod === 'agent' && unsupportedAgentDirectives.length > 0) {
+ if (identitiesOnly) {
+ unsupportedReason ??= `Cindy cannot enforce IdentitiesOnly with ${unsupportedAgentDirectives.join(', ')}`;
+ } else {
+ state.warnings.push(
+ `Host ${alias}: ${unsupportedAgentDirectives.join(', ')} is not interpreted by Cindy; SSH Agent will be used.`,
+ );
+ }
+ }
+ let allowedAgentFingerprints: string[] | undefined;
+ if (authMethod === 'agent' && identitiesOnly && !unsupportedReason) {
+ const resolved = await resolveCompleteFingerprintSet(
+ configuredIdentityFiles,
+ !identityFileDirectiveSeen,
+ fingerprintCache,
+ );
+ allowedAgentFingerprints = resolved.fingerprints;
+ unsupportedReason = resolved.unsupportedReason;
+ }
+
+ hosts.push({
+ id: alias,
+ hostname,
+ port,
+ user,
+ authMethod,
+ identityFile,
+ sshAuthentication: {
+ ...(marker ? { marker } : {}),
+ identitiesOnly,
+ ...(firstMatchingDirective(state.directives, alias, 'identityagent') !== undefined
+ ? { identityAgent: firstMatchingDirective(state.directives, alias, 'identityagent') }
+ : {}),
+ configuredIdentityFiles,
+ identityFileDirectiveSeen,
+ identityFileNoneSeen,
+ ...(allowedAgentFingerprints ? { allowedAgentFingerprints } : {}),
+ ...(unsupportedReason ? { unsupportedReason } : {}),
+ },
+ source: 'ssh-config' as const,
+ managedByCindy: managedOwnership,
+ });
+ }
return hosts;
}
+async function resolveCompleteFingerprintSet(
+ identityFiles: string[],
+ usingDefaults: boolean,
+ cache: Map<string, Promise<IdentityFingerprintResolution>>,
+): Promise<{ fingerprints?: string[]; unsupportedReason?: string }> {
+ const fingerprints: string[] = [];
+ for (const identityFile of identityFiles) {
+ let pending = cache.get(identityFile);
+ if (!pending) {
+ pending = resolveIdentityFingerprints(identityFile);
+ cache.set(identityFile, pending);
+ }
+ const resolved = await pending;
+ if (usingDefaults && resolved.missing) continue;
+ if (resolved.fingerprints.length === 0) {
+ return {
+ unsupportedReason: usingDefaults
+ ? `default identity ${identityFile} exists but Cindy cannot resolve its public key`
+ : `IdentityFile ${identityFile} has no public key Cindy can resolve without reading the private key`,
+ };
+ }
+ for (const fingerprint of resolved.fingerprints) {
+ if (!fingerprints.includes(fingerprint)) fingerprints.push(fingerprint);
+ }
+ }
+ return fingerprints.length > 0
+ ? { fingerprints }
+ : { unsupportedReason: 'IdentitiesOnly yes has no identity Cindy can pin in ssh-agent' };
+}
+
+function matchingDirectives(
+ directives: DirectiveRecord[],
+ alias: string,
+ name: string,
+): DirectiveRecord[] {
+ return directives
+ .filter((directive) => directive.name === name && scopeMatches(directive.scope, alias))
+ .sort((a, b) => a.order - b.order);
+}
+
+function firstMatchingDirective(
+ directives: DirectiveRecord[],
+ alias: string,
+ name: string,
+ scopeFilter: (scope: Scope) => boolean = () => true,
+): string | undefined {
+ return directives
+ .filter((directive) => directive.name === name
+ && scopeFilter(directive.scope)
+ && scopeMatches(directive.scope, alias))
+ .sort((a, b) => a.order - b.order)[0]?.value;
+}
+
+function scopeMatches(scope: Scope, alias: string): boolean {
+ if (scope.kind === 'root') return true;
+ if (scope.kind === 'match') return false;
+ try {
+ return matchesHostPattern(scope.declaration.patterns, alias);
+ } catch {
+ return false;
+ }
+}
+
/**
- * Add a NEW host block to ~/.ssh/config. If a block with the same alias
- * exists it's replaced wholesale (use `updateHostFields` for surgical edits
- * that preserve hand-written directives like ProxyJump / ServerAliveInterval).
- *
- * Atomic write via temp file. Creates the dir + file with strict perms
- * when missing.
+ * OpenSSH host patterns support only `*`, `?`, and a leading `!` negation.
+ * The ssh-config package's glob helper treats `?` as optional (`.?`), which
+ * can apply a wildcard block to the wrong alias (for example `foo?` → `foo`).
*/
-export async function upsertHost(
- host: HostConfig,
- filePath = defaultSshConfigPath(),
-): Promise<void> {
- const existing = await readRawConfig(filePath);
- const parsed = SSHConfig.parse(existing) as SshConfigSection[];
+function matchesHostPattern(patterns: readonly string[], alias: string): boolean {
+ let matched = false;
+ for (const rawPattern of patterns) {
+ const negated = rawPattern.startsWith('!');
+ const pattern = negated ? rawPattern.slice(1) : rawPattern;
+ let source = '^';
+ for (const char of pattern) {
+ if (char === '*') source += '.*';
+ else if (char === '?') source += '.';
+ else source += char.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
+ }
+ source += '$';
+ // OpenSSH host patterns are case-sensitive. Do not pass the `i` flag:
+ // `Host F*` must not match the distinct alias `foo`.
+ if (!new RegExp(source).test(alias)) continue;
+ if (negated) return false;
+ matched = true;
+ }
+ return matched;
+}
- // Remove the complete block before appending the replacement. The ssh-config
- // library's `remove({ Host: alias })` matcher is case-sensitive on the
- // directive name, while OpenSSH treats keywords case-insensitively.
- removeHostSections(parsed, host.id);
+/**
+ * Cindy deliberately does not execute OpenSSH Match expressions. We only
+ * prove a block cannot affect an alias when an `originalhost` criterion
+ * excludes it; every other condition remains conservatively possible.
+ * Match criteria are ANDed, so one definitely-false originalhost condition
+ * is enough to make the whole expression irrelevant to this alias.
+ */
+function matchExpressionMayApplyToAlias(expression: string, alias: string): boolean {
+ const words = splitWords(expression);
+ if (words.length === 0) return true;
+
+ for (let index = 0; index < words.length;) {
+ const criterion = words[index]!.toLowerCase();
+ if (MATCH_NO_ARGUMENT_CRITERIA.has(criterion)) {
+ index += 1;
+ continue;
+ }
+ if (!MATCH_ONE_ARGUMENT_CRITERIA.has(criterion)) return true;
+ const value = words[index + 1];
+ if (value === undefined) return true;
+ if (criterion === 'originalhost' && !matchesMatchPatternList(value, alias)) return false;
+ index += 2;
+ }
+ return true;
+}
+
+/** Match pattern-lists are comma-separated and may contain negated entries. */
+function matchesMatchPatternList(value: string, alias: string): boolean {
+ const patterns = value.split(',').filter(Boolean);
+ if (patterns.length === 0) return true;
- const append = SSHConfig.parse(formatHostBlock(host)) as SshConfigSection[];
- for (const node of append) {
- (parsed as unknown as { push(node: unknown): void }).push(node);
+ let hasPositive = false;
+ let positiveMatched = false;
+ for (const rawPattern of patterns) {
+ const negated = rawPattern.startsWith('!');
+ const pattern = negated ? rawPattern.slice(1) : rawPattern;
+ if (!pattern) return true;
+ const matches = matchesHostPattern([pattern], alias);
+ if (negated && matches) return false;
+ if (!negated) {
+ hasPositive = true;
+ positiveMatched ||= matches;
+ }
}
+ return hasPositive ? positiveMatched : true;
+}
- const out = (parsed as unknown as { toString(): string }).toString();
- await writeAtomic(filePath, out);
+function isSupportedIncludeScope(scope: Scope): boolean {
+ return scope.kind === 'root'
+ || (scope.kind === 'host'
+ && scope.declaration.patterns.length === 1
+ && scope.declaration.patterns[0] === '*');
}
-/** Remove all concrete Host blocks for an alias, regardless of keyword casing. */
-function removeHostSections(parsed: SshConfigSection[], alias: string): void {
- for (let index = parsed.length - 1; index >= 0; index -= 1) {
- const section = parsed[index];
- if (!isHostDirective(section)) continue;
- const values = Array.isArray(section.value) ? section.value : [section.value];
- if (values.includes(alias)) parsed.splice(index, 1);
+function parseDirectiveLine(line: string): { keyword: string; value: string } | null {
+ if (!line || line.startsWith('#')) return null;
+ const match = /^([^\s=#]+)(?:\s*=\s*|\s+)(.*)$/.exec(line);
+ if (match) return { keyword: match[1]!.toLowerCase(), value: match[2]!.trim() };
+ return { keyword: line.toLowerCase(), value: '' };
+}
+
+function splitWords(value: string): string[] {
+ const words: string[] = [];
+ let word = '';
+ let quote: '"' | "'" | null = null;
+ const push = (): void => {
+ if (!word) return;
+ words.push(word);
+ word = '';
+ };
+ for (let index = 0; index < value.length; index += 1) {
+ const char = value[index]!;
+ if (quote) {
+ if (char === quote) quote = null;
+ else if (char === '\\'
+ && quote === '"'
+ && (value[index + 1] === '"' || value[index + 1] === '\\')) {
+ word += value[index + 1];
+ index += 1;
+ } else word += char;
+ continue;
+ }
+ if (char === '#') {
+ if (!word) break;
+ word += char;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (/\s/.test(char)) {
+ push();
+ continue;
+ }
+ if (char === '\\' && /[\s#'"\\]/.test(value[index + 1] ?? '')) {
+ word += value[index + 1];
+ index += 1;
+ continue;
+ }
+ word += char;
+ }
+ push();
+ return words;
+}
+
+function firstWordOrRaw(value: string): string {
+ return splitWords(value)[0] ?? value.trim();
+}
+
+function parseAuthMarker(comment: string): AuthMarker | null {
+ const normalized = comment.trim();
+ if (normalized === `${AUTH_MARKER_PREFIX}agent`) return 'agent';
+ if (normalized === `${AUTH_MARKER_PREFIX}key`) return 'key';
+ return null;
+}
+
+function hasManagedConfigMarker(raw: string): boolean {
+ const firstContentLine = raw.split(/\r?\n/).find((line) => line.trim() !== '');
+ return firstContentLine?.trim() === MANAGED_CONFIG_MARKER;
+}
+
+function isCanonicalizationDirective(keyword: string): boolean {
+ return keyword.startsWith('canonicalize') || keyword === 'canonicaldomains';
+}
+
+function isConcreteAlias(alias: string): boolean {
+ return !!alias
+ && !alias.includes('*')
+ && !alias.includes('?')
+ && !alias.includes('[')
+ && !alias.startsWith('!');
+}
+
+interface IdentityFileTokenContext {
+ alias: string;
+ hostname: string;
+ user: string;
+ port: number;
+ hostKeyAlias?: string;
+ proxyJump?: string;
+}
+
+type IdentityFileExpansionResult =
+ | { filePath: string }
+ | { unsupportedToken: string };
+
+/** Expand IdentityFile tokens once using the effective host connection context. */
+function expandIdentityFile(
+ value: string,
+ context: IdentityFileTokenContext,
+): IdentityFileExpansionResult {
+ const localUser = os.userInfo();
+ const localHostname = os.hostname();
+ const proxyJump = context.proxyJump ?? '';
+ const connectionHash = createHash('sha1').update(
+ `${localHostname}${context.hostname}${context.port}${context.user}${proxyJump}`,
+ ).digest('hex');
+ const replacements: Record<string, string> = {
+ '%': '%',
+ C: connectionHash,
+ d: os.homedir(),
+ h: context.hostname,
+ i: String(localUser.uid),
+ j: proxyJump,
+ k: context.hostKeyAlias ?? context.alias,
+ L: localHostname.split('.')[0] ?? localHostname,
+ l: localHostname,
+ n: context.alias,
+ p: String(context.port),
+ r: context.user,
+ u: localUser.username,
+ };
+ let expanded = '';
+ for (let index = 0; index < value.length; index += 1) {
+ const char = value[index]!;
+ if (char !== '%') {
+ expanded += char;
+ continue;
+ }
+ const token = value[index + 1];
+ if (token === undefined || replacements[token] === undefined) {
+ return { unsupportedToken: token === undefined ? '%' : `%${token}` };
+ }
+ expanded += replacements[token];
+ index += 1;
}
+ expanded = expandHome(expanded);
+ // Unlike Include, OpenSSH does not resolve a relative IdentityFile against
+ // the config file directory. It remains relative to the ssh process cwd.
+ return {
+ filePath: path.isAbsolute(expanded) ? expanded : path.resolve(process.cwd(), expanded),
+ };
+}
+
+async function globPaths(pattern: string): Promise<string[]> {
+ const normalized = path.normalize(pattern);
+ const root = path.parse(normalized).root;
+ const segments = normalized.slice(root.length).split(path.sep).filter(Boolean);
+ const start = root || '.';
+
+ const walk = async (directory: string, index: number): Promise<string[]> => {
+ if (index >= segments.length) {
+ try {
+ const stat = await fs.stat(directory);
+ return stat.isFile() ? [directory] : [];
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === 'ENOENT' || code === 'ENOTDIR') return [];
+ throw error;
+ }
+ }
+
+ const segment = segments[index]!;
+ if (!hasGlob(segment)) return walk(path.join(directory, segment), index + 1);
+
+ let entries: string[];
+ try {
+ entries = (await fs.readdir(directory)).sort((a, b) =>
+ Buffer.compare(Buffer.from(a), Buffer.from(b)));
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === 'ENOENT' || code === 'ENOTDIR') return [];
+ throw error;
+ }
+
+ const matches: string[] = [];
+ for (const entry of entries) {
+ if (entry.startsWith('.') && !segment.startsWith('.')) continue;
+ if (path.matchesGlob(entry, segment)) {
+ matches.push(...await walk(path.join(directory, entry), index + 1));
+ }
+ }
+ return matches;
+ };
+
+ return walk(start, 0);
+}
+
+function hasGlob(value: string): boolean {
+ return /[*?\[]/.test(value);
+}
+
+/** Ensure the main config has one supported, canonical exact Include. */
+export async function ensureManagedConfigInclude(
+ mainConfigPath: string,
+ managedConfigPath: string,
+): Promise<void> {
+ const managedExisting = await readRawConfig(managedConfigPath);
+ if (managedExisting) assertManagedConfigOwnership(managedExisting);
+ const existing = await readRawConfig(mainConfigPath);
+ const eol = existing.includes('\r\n') ? '\r\n' : '\n';
+ const lines = splitLinesKeepingEndings(existing);
+ const kept: string[] = [];
+ const movedInlineComments: string[] = [];
+ let scope: 'root' | 'pure-star' | 'conditional' | 'match' = 'root';
+
+ for (const line of lines) {
+ const directive = parseDirectiveLine(line.trim());
+ if (directive?.keyword === 'host') {
+ const patterns = splitWords(directive.value);
+ scope = patterns.length === 1 && patterns[0] === '*' ? 'pure-star' : 'conditional';
+ } else if (directive?.keyword === 'match') {
+ scope = 'match';
+ }
+
+ const supported = scope === 'root' || scope === 'pure-star';
+ if (supported
+ && directive?.keyword === 'include'
+ && await isSingleExactInclude(
+ directive.value,
+ path.dirname(path.resolve(mainConfigPath)),
+ managedConfigPath,
+ )) {
+ const inlineComment = extractInlineComment(stripLineEnding(line));
+ if (inlineComment && !movedInlineComments.includes(inlineComment)) {
+ movedInlineComments.push(inlineComment);
+ }
+ continue;
+ }
+ kept.push(line);
+ }
+
+ let insertionIndex = 0;
+ while (insertionIndex < kept.length) {
+ const content = stripLineEnding(kept[insertionIndex]!).trim();
+ if (content === '' || content.startsWith('#')) insertionIndex += 1;
+ else break;
+ }
+ const [firstInlineComment, ...extraInlineComments] = movedInlineComments;
+ const includeLine = `Include ${formatIncludePath(managedConfigPath)}`
+ + `${firstInlineComment ? ` ${firstInlineComment}` : ''}${eol}`;
+ const preservedExtraComments = extraInlineComments.map((comment) => `${comment}${eol}`);
+ kept.splice(insertionIndex, 0, includeLine, ...preservedExtraComments);
+ if (insertionIndex > 0 && !/[\r\n]$/.test(kept[insertionIndex - 1]!)) {
+ kept[insertionIndex - 1] = `${kept[insertionIndex - 1]}${eol}`;
+ }
+ const next = kept.join('');
+ if (next !== existing) {
+ await writeAtomicPreservingTarget(mainConfigPath, next, existing);
+ }
+}
+
+/** Append a new, single-alias Host block to Cindy's managed file. */
+export async function addManagedHost(host: HostConfig, managedConfigPath: string): Promise<void> {
+ const existing = await readRawConfig(managedConfigPath);
+ const next = prepareManagedHostAdd(host, existing);
+ await writeAtomicPreservingTarget(managedConfigPath, next, existing);
}
/**
- * Surgically update only the fields we own (HostName / User / Port /
- * IdentityFile / IdentitiesOnly) inside an existing host block, leaving
- * everything else (ProxyJump / ServerAliveInterval / Tag / comments / ...)
- * exactly as the user wrote them.
- *
- * Falls back to `upsertHost` if the host block doesn't exist on disk
- * (e.g. user removed it manually since we last hydrated).
- *
- * Updating an already-set directive mutates its `.value` in place — the
- * surrounding whitespace / comments are preserved by ssh-config's
- * `.toString()` serializer.
- *
- * Adding a new directive (e.g. switching from agent to key requires
- * inserting `IdentityFile`) appends to the block's nested config array
- * with synthesized whitespace that matches OpenSSH's convention (2-space
- * indent + trailing newline).
- *
- * Removing a directive (e.g. switching from key back to agent should drop
- * `IdentityFile` and `IdentitiesOnly`) is a `.filter` on the block's
- * nested config array.
+ * Publish a new managed host without ever making a known-bad managed file
+ * reachable from the user's main SSH config.
*/
-export async function updateHostFields(
+export async function addManagedHostWithInclude(
host: HostConfig,
- filePath = defaultSshConfigPath(),
+ mainConfigPath: string,
+ managedConfigPath: string,
+): Promise<ManagedHostAddReceipt> {
+ const existing = await readRawConfig(managedConfigPath);
+ assertManagedConfigOwnership(existing);
+ // Parse and serialize the complete next file before publishing either disk
+ // mutation. A malformed pre-existing cindy.conf therefore cannot be exposed
+ // by a newly inserted Include.
+ const next = prepareManagedHostAdd(host, existing);
+ await writeAtomicPreservingTarget(managedConfigPath, next, existing);
+ try {
+ await ensureManagedConfigInclude(mainConfigPath, managedConfigPath);
+ } catch (includeError) {
+ // Roll back only if nobody changed the managed file after our atomic write.
+ // If it did change, preserving that external edit is safer; both versions
+ // are syntactically valid, so the main SSH graph is not poisoned.
+ try {
+ await restoreManagedConfigIfUnchanged(managedConfigPath, next, existing);
+ } catch (rollbackError) {
+ throw new AggregateError(
+ [includeError, rollbackError],
+ 'failed to publish managed SSH Include and roll back the staged host',
+ );
+ }
+ throw includeError;
+ }
+ return {
+ rollback: () => restoreManagedConfigIfUnchanged(managedConfigPath, next, existing),
+ };
+}
+
+/** Update only Cindy-owned connection fields and preserve all other directives. */
+export async function updateManagedHostFields(
+ host: HostConfig,
+ managedConfigPath: string,
+ expectedToken: ManagedConfigWriteToken,
): Promise<void> {
+ assertManagedWriteToken(expectedToken);
+ const existingBytes = await readRawConfigBytes(managedConfigPath);
+ assertManagedConfigUnchanged(existingBytes, expectedToken);
+ const existing = existingBytes.toString('utf8');
+ assertManagedConfigOwnership(existing);
+ if (!existing) throw new Error(`managed SSH host not found: ${host.id}`);
+ const parsed = SSHConfig.parse(existing) as SshConfigSection[];
+ const section = findSingleHostSection(parsed, host.id);
+ if (!section?.config) throw new Error(`managed SSH host not found or ambiguous: ${host.id}`);
+ projectManagedFields(section, host, existing.includes('\r\n') ? '\r\n' : '\n');
+ await writeAtomicPreservingTarget(
+ managedConfigPath,
+ (parsed as unknown as { toString(): string }).toString(),
+ existing,
+ );
+}
+
+export async function removeManagedHost(
+ alias: string,
+ managedConfigPath: string,
+ expectedToken: ManagedConfigWriteToken,
+): Promise<void> {
+ assertManagedWriteToken(expectedToken);
+ const existingBytes = await readRawConfigBytes(managedConfigPath);
+ assertManagedConfigUnchanged(existingBytes, expectedToken);
+ const existing = existingBytes.toString('utf8');
+ assertManagedConfigOwnership(existing);
+ if (!existing) return;
+ const parsed = SSHConfig.parse(existing) as SshConfigSection[];
+ const matches = parsed.filter((section) => isSingleAliasHostSection(section, alias));
+ if (matches.length !== 1) throw new Error(`managed SSH host not found or ambiguous: ${alias}`);
+ parsed.splice(parsed.indexOf(matches[0]!), 1);
+ await writeAtomicPreservingTarget(
+ managedConfigPath,
+ (parsed as unknown as { toString(): string }).toString(),
+ existing,
+ );
+}
+
+/** Legacy helpers retained for package callers/tests. Every path is required. */
+export async function upsertHost(host: HostConfig, filePath: string): Promise<void> {
const existing = await readRawConfig(filePath);
- if (!existing) {
- return upsertHost(host, filePath);
- }
const parsed = SSHConfig.parse(existing) as SshConfigSection[];
+ removeHostSections(parsed, host.id);
+ const append = SSHConfig.parse(formatHostBlock(host, '\n')) as SshConfigSection[];
+ for (const node of append) (parsed as unknown as { push(node: unknown): void }).push(node);
+ await writeAtomicPreservingTarget(
+ filePath,
+ (parsed as unknown as { toString(): string }).toString(),
+ existing,
+ );
+}
+export async function updateHostFields(host: HostConfig, filePath: string): Promise<void> {
+ const existing = await readRawConfig(filePath);
+ if (!existing) return upsertHost(host, filePath);
+ const parsed = SSHConfig.parse(existing) as SshConfigSection[];
const section = findHostSection(parsed, host.id);
- if (!section || !section.config) {
- // Block disappeared since we hydrated — recreate it cleanly. Caller's
- // pool will end up consistent with disk on next hydrate.
- return upsertHost(host, filePath);
- }
-
- // Build the (param, value-or-null) directives we want to project onto
- // the existing block. `null` = remove the directive entirely; a value
- // = set / replace.
- // Both auth modes can carry an identityFile:
- // key → identityFile is the private key we read directly (no agent).
- // agent → identityFile is the public key we filter the agent down to.
- // In both cases we want OpenSSH CLI to mirror the behaviour — that means
- // IdentityFile + IdentitiesOnly yes so a terminal `ssh <alias>` doesn't
- // enumerate every agent key and trip MaxAuthTries.
- const hasPinnedKey = !!host.identityFile;
+ if (!section?.config) return upsertHost(host, filePath);
+ projectManagedFields(section, host, existing.includes('\r\n') ? '\r\n' : '\n');
+ await writeAtomicPreservingTarget(
+ filePath,
+ (parsed as unknown as { toString(): string }).toString(),
+ existing,
+ );
+}
+
+export async function removeHost(alias: string, filePath: string): Promise<void> {
+ const existing = await readRawConfig(filePath);
+ if (!existing) return;
+ const parsed = SSHConfig.parse(existing) as SshConfigSection[];
+ removeHostSections(parsed, alias);
+ await writeAtomicPreservingTarget(
+ filePath,
+ (parsed as unknown as { toString(): string }).toString(),
+ existing,
+ );
+}
+
+function projectManagedFields(section: SshConfigSection, host: HostConfig, eol: string): void {
+ const hasIdentity = !!host.identityFile;
const desired: Array<[string, string | null]> = [
['HostName', host.hostname],
['User', host.user],
['Port', host.port && host.port !== DEFAULT_PORT ? String(host.port) : null],
- ['IdentityFile', hasPinnedKey ? host.identityFile! : null],
- ['IdentitiesOnly', hasPinnedKey ? 'yes' : null],
+ ['IdentityFile', hasIdentity ? host.identityFile! : null],
+ ['IdentitiesOnly', hasIdentity ? 'yes' : null],
];
+ for (const [name, value] of desired) applyDirective(section, name, value, eol);
+ // Always persist Cindy's auth choice. Without an agent marker, a managed
+ // host with no local IdentityFile would silently become key auth if it
+ // inherits an IdentityFile from an earlier Host * block.
+ applyAuthMarker(section, host.authMethod, eol);
+}
- for (const [param, value] of desired) {
- applyDirective(section, param, value);
- }
- // Marker comment lives alongside the directives. Set/clear it based on
- // the post-edit auth method so we recover the choice on next read.
- applyAuthMarker(section, hasPinnedKey ? host.authMethod : null);
+function findAnyHostSection(parsed: SshConfigSection[], alias: string): SshConfigSection | null {
+ return parsed.find((section) => isHostDirective(section)
+ && directiveValues(section).includes(alias)) ?? null;
+}
- const out = (parsed as unknown as { toString(): string }).toString();
- await writeAtomic(filePath, out);
+function findHostSection(parsed: SshConfigSection[], alias: string): SshConfigSection | null {
+ return findAnyHostSection(parsed, alias);
}
-/** Find a Host section whose value list contains exactly `alias`. */
-function findHostSection(
- parsed: SshConfigSection[],
- alias: string,
-): SshConfigSection | null {
- for (const section of parsed) {
- if (!isHostDirective(section)) continue;
- const values = Array.isArray(section.value) ? section.value : [section.value];
- if (values.includes(alias)) return section;
+function findSingleHostSection(parsed: SshConfigSection[], alias: string): SshConfigSection | null {
+ const matches = parsed.filter((section) => isSingleAliasHostSection(section, alias));
+ return matches.length === 1 ? matches[0]! : null;
+}
+
+function isSingleAliasHostSection(section: SshConfigSection, alias: string): boolean {
+ const values = directiveValues(section);
+ return isHostDirective(section) && values.length === 1 && values[0] === alias;
+}
+
+function isHostDirective(section: SshConfigSection): boolean {
+ return section.param?.toLowerCase() === 'host';
+}
+
+function directiveValues(section: SshConfigSection): string[] {
+ const raw = Array.isArray(section.value) ? section.value : [section.value];
+ const values: string[] = [];
+ for (const item of raw) {
+ if (typeof item === 'string') values.push(item);
+ else if (item && typeof item.val === 'string') values.push(item.val);
+ }
+ return values;
+}
+
+function removeHostSections(parsed: SshConfigSection[], alias: string): void {
+ for (let index = parsed.length - 1; index >= 0; index -= 1) {
+ if (isHostDirective(parsed[index]!) && directiveValues(parsed[index]!).includes(alias)) {
+ parsed.splice(index, 1);
+ }
}
- return null;
}
-/**
- * Within a Host block's nested directive list, either:
- * - set the named directive's value (mutates first matching entry, drops
- * any duplicate matches — multiple `IdentityFile` lines collapse to one,
- * which is the right behavior for our managed fields), OR
- * - remove all matching directives entirely if `value === null`.
- *
- * Matches are case-insensitive (SSH config keys are).
- */
function applyDirective(
section: SshConfigSection,
param: string,
value: string | null,
+ eol: string,
): void {
const children = section.config ?? [];
- const lowerParam = param.toLowerCase();
-
+ const wanted = param.toLowerCase();
if (value === null) {
- section.config = children.filter(
- (c) => !c.param || c.param.toLowerCase() !== lowerParam,
- );
+ section.config = children.filter((child) => child.param?.toLowerCase() !== wanted);
return;
}
-
- let matched = false;
+ const serialized = serializeSshValue(value);
+ let found = false;
const next: SshConfigSection[] = [];
for (const child of children) {
- if (child.param && child.param.toLowerCase() === lowerParam) {
- if (matched) continue; // drop dupes — only keep the first
- matched = true;
- child.value = value;
- next.push(child);
- } else {
- next.push(child);
- }
- }
- if (!matched) {
- // Insert a fresh directive at the end of the block. Whitespace matches
- // the rest of the block — 2-space indent + trailing newline is the
- // OpenSSH convention `formatHostBlock` also emits.
+ if (child.param?.toLowerCase() === wanted) {
+ if (found) continue;
+ child.value = serialized.value;
+ child.quoted = serialized.quoted || undefined;
+ found = true;
+ }
+ next.push(child);
+ }
+ if (!found) {
next.push({
type: SSH_CONFIG_DIRECTIVE_TYPE,
before: ' ',
- after: '\n',
+ after: eol,
param,
- // Without a separator the serializer emits `<param>undefined<value>`,
- // producing an unparseable directive that corrupts ~/.ssh/config.
separator: ' ',
- value,
+ value: serialized.value,
+ quoted: serialized.quoted || undefined,
});
}
section.config = next;
}
-/**
- * Set/clear the `# xdt-maker:auth=...` marker comment inside a host block.
- *
- * Called from `updateHostFields` so the round-trip preserves the user's
- * choice between 'agent + pinned key' and 'key' modes (both share the
- * same `IdentityFile + IdentitiesOnly yes` directives on disk).
- *
- * Passing `method = null` removes any existing marker (used when the
- * directives that warrant it are themselves being removed).
- */
function applyAuthMarker(
section: SshConfigSection,
- method: 'agent' | 'key' | null,
+ method: AuthMarker,
+ eol: string,
): void {
const children = section.config ?? [];
- // Drop any existing marker first — handles toggling between agent/key
- // as well as the clear-on-removal case.
- const cleaned = children.filter((c) => {
- if (c.type !== SSH_CONFIG_COMMENT_TYPE) return true;
- const content = (c.content ?? '').trim();
- return !content.startsWith(AUTH_MARKER_PREFIX);
- });
- if (method === null) {
- section.config = cleaned;
- return;
- }
- cleaned.push({
+ const next = children.filter((child) => !(child.type === SSH_CONFIG_COMMENT_TYPE
+ && (child.content ?? '').trim().startsWith(AUTH_MARKER_PREFIX)));
+ const identityIndex = next.findIndex((child) => child.param?.toLowerCase() === 'identityfile');
+ const marker: SshConfigSection = {
type: SSH_CONFIG_COMMENT_TYPE,
before: ' ',
- after: '\n',
+ after: eol,
content: `${AUTH_MARKER_PREFIX}${method}`,
- });
- section.config = cleaned;
+ };
+ next.splice(identityIndex >= 0 ? identityIndex : next.length, 0, marker);
+ section.config = next;
}
-/** Drop a host block. No-op if absent. */
-export async function removeHost(
- alias: string,
- filePath = defaultSshConfigPath(),
-): Promise<void> {
- const existing = await readRawConfig(filePath);
- if (!existing) return;
- const parsed = SSHConfig.parse(existing) as SshConfigSection[];
- removeHostSections(parsed, alias);
- await writeAtomic(filePath, (parsed as unknown as { toString(): string }).toString());
+function formatHostBlock(host: HostConfig, eol: string): string {
+ assertManagedAlias(host.id);
+ const parsed = SSHConfig.parse(
+ `Host ${formatSshArgument(host.id)}${eol}`,
+ ) as SshConfigSection[];
+ const section = parsed[0];
+ if (!section) throw new Error(`failed to construct managed SSH host: ${host.id}`);
+ projectManagedFields(section, host, eol);
+ return (parsed as unknown as { toString(): string }).toString();
}
-// ── internals ──────────────────────────────────────────────────────────────
+function prepareManagedHostAdd(host: HostConfig, existing: string): string {
+ const ownedExisting = assertManagedConfigOwnership(existing);
+ const parsed = SSHConfig.parse(ownedExisting) as SshConfigSection[];
+ if (findAnyHostSection(parsed, host.id)) {
+ throw new Error(`host already exists in managed SSH config: ${host.id}`);
+ }
+ const eol = existing.includes('\r\n') ? '\r\n' : '\n';
+ const separator = existing && !existing.endsWith('\n') && !existing.endsWith('\r') ? eol : '';
+ const next = `${ownedExisting}${separator}${formatHostBlock(host, eol)}`;
+ // The package parser is also the syntax gate used by discovery. Reparse the
+ // exact bytes that will be written so escaping changes cannot publish an
+ // unreadable managed file.
+ SSHConfig.parse(next);
+ return next;
+}
+
+function assertManagedConfigOwnership(existing: string): string {
+ if (!existing.trim()) return `${MANAGED_CONFIG_MARKER}\n`;
+ if (!hasManagedConfigMarker(existing)) {
+ const error = new Error(
+ 'existing managed SSH config is not owned by Cindy; add the Cindy ownership marker or choose another file',
+ ) as Error & { code?: string };
+ error.code = MANAGED_CONFIG_OWNERSHIP_REQUIRED_CODE;
+ throw error;
+ }
+ return existing;
+}
+
+async function isSingleExactInclude(
+ value: string,
+ configDir: string,
+ managedConfigPath: string,
+): Promise<boolean> {
+ const patterns = splitWords(value);
+ if (patterns.length !== 1 || hasGlob(patterns[0]!)) return false;
+ const expansion = expandIncludePath(patterns[0]!);
+ if ('warning' in expansion) return false;
+ const expanded = expansion.pattern;
+ const resolved = path.isAbsolute(expanded) ? expanded : path.resolve(configDir, expanded);
+ return pathsEqual(await comparablePath(resolved), await comparablePath(managedConfigPath));
+}
+
+function formatIncludePath(managedConfigPath: string): string {
+ const absolute = path.resolve(managedConfigPath);
+ const defaultPath = path.resolve(defaultManagedSshConfigPath());
+ const value = pathsEqual(absolute, defaultPath) ? '~/.ssh/cindy.conf' : absolute;
+ return formatSshArgument(value);
+}
+
+function serializeSshValue(value: string): { value: string; quoted: boolean } {
+ assertSafeSshValue(value);
+ const quoted = value === '' || value.startsWith('#') || /[\s"\\]/.test(value);
+ return {
+ value: quoted
+ ? value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
+ : value,
+ quoted,
+ };
+}
+
+function formatSshArgument(value: string): string {
+ const serialized = serializeSshValue(value);
+ return serialized.quoted ? `"${serialized.value}"` : serialized.value;
+}
+
+function assertSafeSshValue(value: string): void {
+ if (/[\0\r\n]/.test(value)) {
+ throw new Error('SSH config values must not contain NUL or line breaks');
+ }
+}
+
+function assertManagedAlias(alias: string): void {
+ assertSafeSshValue(alias);
+ if (!alias
+ || /\s/.test(alias)
+ || alias.includes('*')
+ || alias.includes('?')
+ || alias.includes('[')
+ || alias.startsWith('!')) {
+ throw new Error(`invalid managed SSH alias: ${alias}`);
+ }
+}
+
+function splitLinesKeepingEndings(value: string): string[] {
+ if (!value) return [];
+ return value.match(/.*(?:\r\n|\n|\r|$)/g)?.filter(Boolean) ?? [];
+}
+
+function stripLineEnding(value: string): string {
+ return value.replace(/[\r\n]+$/, '');
+}
+
+/** Return an OpenSSH inline comment; token-internal `#` is ordinary text. */
+function extractInlineComment(line: string): string | null {
+ let quote: '"' | "'" | null = null;
+ for (let index = 0; index < line.length; index += 1) {
+ const char = line[index]!;
+ if (quote) {
+ if (char === quote) quote = null;
+ else if (char === '\\' && quote === '"') index += 1;
+ continue;
+ }
+ if (char === '\\') {
+ index += 1;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '#' && (index === 0 || /\s/.test(line[index - 1]!))) {
+ return line.slice(index).trimEnd();
+ }
+ }
+ return null;
+}
async function readRawConfig(filePath: string): Promise<string> {
try {
return await fs.readFile(filePath, 'utf8');
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code === 'ENOENT') return '';
- throw err;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return '';
+ throw error;
+ }
+}
+
+async function readRawConfigBytes(filePath: string): Promise<Buffer> {
+ try {
+ return await fs.readFile(filePath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return Buffer.alloc(0);
+ throw error;
}
}
-async function writeAtomic(filePath: string, content: string): Promise<void> {
- await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
- const tmp = `${filePath}.maker.tmp`;
- await fs.writeFile(tmp, content, { mode: 0o600 });
- await fs.rename(tmp, filePath);
+function managedConfigToken(bytes: Uint8Array): ManagedConfigWriteToken {
+ return createHash('sha256').update(bytes).digest('hex') as ManagedConfigWriteToken;
}
-function formatHostBlock(host: HostConfig): string {
- const lines = [
- `Host ${host.id}`,
- ` HostName ${host.hostname}`,
- ` User ${host.user}`,
- ];
- if (host.port && host.port !== DEFAULT_PORT) lines.push(` Port ${host.port}`);
- // identityFile is meaningful for BOTH auth methods (private key for 'key',
- // public key fingerprint source for 'agent' pin). Either way, pair it with
- // IdentitiesOnly yes so terminal `ssh <alias>` doesn't enumerate every
- // agent key and trigger MaxAuthTries. We also stamp an `# xdt-maker:auth=`
- // marker so on re-read we can distinguish 'agent + pinned' from 'key'.
- if (host.identityFile) {
- lines.push(` ${AUTH_MARKER_PREFIX}${host.authMethod}`);
- lines.push(` IdentityFile ${host.identityFile}`);
- lines.push(' IdentitiesOnly yes');
+function assertManagedWriteToken(
+ token: ManagedConfigWriteToken | undefined,
+): asserts token is ManagedConfigWriteToken {
+ if (typeof token === 'string' && /^[a-f0-9]{64}$/.test(token)) return;
+ const error = new Error('managed SSH config write token is required') as Error & { code?: string };
+ error.code = MANAGED_CONFIG_WRITE_TOKEN_REQUIRED_CODE;
+ throw error;
+}
+
+function assertManagedConfigUnchanged(
+ currentBytes: Uint8Array,
+ expectedToken: ManagedConfigWriteToken,
+): void {
+ if (managedConfigToken(currentBytes) === expectedToken) return;
+ const conflict = new Error(
+ 'SSH config changed after Cindy validated it; reload before retrying.',
+ ) as Error & { code?: string };
+ conflict.code = MANAGED_CONFIG_CONCURRENT_MODIFICATION_CODE;
+ throw conflict;
+}
+
+async function writeAtomicPreservingTarget(
+ filePath: string,
+ content: string,
+ expectedContent: string,
+): Promise<void> {
+ const requested = path.resolve(filePath);
+ let target = requested;
+ let existingMode: number | undefined;
+ try {
+ const lstat = await fs.lstat(requested);
+ if (lstat.isSymbolicLink()) target = await fs.realpath(requested);
+ const stat = await fs.stat(target);
+ existingMode = stat.mode & 0o777;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ let requestedIsSymlink = false;
+ try {
+ const lstat = await fs.lstat(requested);
+ requestedIsSymlink = lstat.isSymbolicLink();
+ } catch (lstatError) {
+ if ((lstatError as NodeJS.ErrnoException).code !== 'ENOENT') throw lstatError;
+ }
+ if (requestedIsSymlink) throw error;
+ }
+
+ await fs.mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
+ const tempPath = path.join(
+ path.dirname(target),
+ `.${path.basename(target)}.cindy-${process.pid}-${randomBytes(6).toString('hex')}`,
+ );
+ try {
+ await fs.writeFile(tempPath, content, { flag: 'wx', mode: existingMode ?? 0o600 });
+ if (existingMode !== undefined) await fs.chmod(tempPath, existingMode);
+ if (await readRawConfig(target) !== expectedContent) {
+ const conflict = new Error(
+ 'SSH config changed while Cindy was preparing an update; retry the operation.',
+ ) as Error & { code?: string };
+ conflict.code = MANAGED_CONFIG_CONCURRENT_MODIFICATION_CODE;
+ throw conflict;
+ }
+ await fs.rename(tempPath, target);
+ } catch (error) {
+ await fs.unlink(tempPath).catch(() => undefined);
+ throw error;
+ }
+}
+
+async function restoreManagedConfigIfUnchanged(
+ managedConfigPath: string,
+ publishedContent: string,
+ previousContent: string,
+): Promise<boolean> {
+ if (await readRawConfig(managedConfigPath) !== publishedContent) return false;
+ try {
+ await writeAtomicPreservingTarget(managedConfigPath, previousContent, publishedContent);
+ return true;
+ } catch (error) {
+ if ((error as { code?: string }).code === MANAGED_CONFIG_CONCURRENT_MODIFICATION_CODE) return false;
+ throw error;
+ }
+}
+
+async function comparablePath(value: string): Promise<string> {
+ const absolute = path.resolve(expandHome(value));
+ let comparable = absolute;
+ try {
+ comparable = await fs.realpath(absolute);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ comparable = path.normalize(comparable);
+ return process.platform === 'win32' ? comparable.toLowerCase() : comparable;
+}
+
+function pathsEqual(left: string, right: string): boolean {
+ return process.platform === 'win32'
+ ? left.toLowerCase() === right.toLowerCase()
+ : left === right;
+}
+
+async function pathExists(value: string): Promise<boolean> {
+ try {
+ await fs.access(value);
+ return true;
+ } catch {
+ return false;
}
- // Leading blank line keeps blocks visually separated; trailing newline ends the block.
- return `\n${lines.join('\n')}\n`;
}
function parseIntSafe(value: string | undefined, fallback: number): number {
if (!value) return fallback;
- const n = parseInt(value, 10);
- return Number.isFinite(n) ? n : fallback;
+ const parsed = Number.parseInt(value, 10);
+ return Number.isFinite(parsed) ? parsed : fallback;
+}
+
+function limitError(pathName: string, message: string): Error & { code: string; path: string } {
+ const error = new Error(message) as Error & { code: string; path: string };
+ error.code = 'SSH_CONFIG_LIMIT';
+ error.path = pathName;
+ return error;
+}
+
+function toConfigDiagnostic(filePath: string, error: unknown): SshConfigDiagnostic {
+ const code = (error as { code?: string }).code;
+ const kind: SshConfigDiagnostic['kind'] = code === 'SSH_CONFIG_LIMIT'
+ ? 'limit'
+ : code === 'SSH_CONFIG_SYNTAX'
+ ? 'syntax'
+ : 'io';
+ return {
+ path: typeof (error as { path?: unknown }).path === 'string'
+ ? (error as { path: string }).path
+ : filePath,
+ kind,
+ message: error instanceof Error ? error.message : String(error),
+ recoveryHint: kind === 'syntax'
+ ? 'Fix the SSH config syntax, then refresh.'
+ : kind === 'limit'
+ ? 'Reduce Include nesting, file count, or config size, then refresh.'
+ : 'Check SSH config permissions and Include paths, then refresh.',
+ };
}
diff --git a/packages/maker-remote-ssh/src/sshRedaction.ts b/packages/maker-remote-ssh/src/sshRedaction.ts
new file mode 100644
index 0000000000..de14743cc8
--- /dev/null
+++ b/packages/maker-remote-ssh/src/sshRedaction.ts
@@ -0,0 +1,64 @@
+import { previewAgentEndpoint } from './sshAuthentication.js';
+
+interface SensitiveSshConfig {
+ identityFile?: string;
+ sshAuthentication?: {
+ identityAgent?: string;
+ configuredIdentityFiles?: string[];
+ };
+}
+
+interface Replacement {
+ value: string;
+ replacement: '<identity-agent>' | '<identity-file>';
+}
+
+/**
+ * Remove local credential paths immediately before text crosses a trusted
+ * boundary. Resolved Agent endpoints are deliberately computed on demand and
+ * never stored on HostConfig or HostSnapshot.
+ */
+export function redactSshSensitiveText(
+ config: SensitiveSshConfig,
+ text: string,
+): string {
+ const replacements = credentialReplacements(config);
+ let redacted = text;
+ for (const { value, replacement } of replacements) {
+ redacted = redacted.split(value).join(replacement);
+ }
+ return redacted;
+}
+
+function credentialReplacements(
+ config: SensitiveSshConfig,
+): Replacement[] {
+ const byValue = new Map<string, Replacement['replacement']>();
+ const add = (value: string | undefined, replacement: Replacement['replacement']): void => {
+ if (!value || value.trim() === '') return;
+ // OpenSSH's lowercase sentinel is behavior, not a sensitive endpoint, and
+ // replacing the ordinary word "none" would corrupt unrelated diagnostics.
+ if (replacement === '<identity-agent>' && value === 'none') return;
+ const previous = byValue.get(value);
+ if (previous === undefined || replacement === '<identity-agent>') {
+ byValue.set(value, replacement);
+ }
+ };
+
+ add(config.identityFile, '<identity-file>');
+ for (const value of config.sshAuthentication?.configuredIdentityFiles ?? []) {
+ add(value, '<identity-file>');
+ }
+
+ const identityAgent = config.sshAuthentication?.identityAgent;
+ add(identityAgent, '<identity-agent>');
+ add(previewAgentEndpoint(identityAgent).endpoint, '<identity-agent>');
+
+ return Array.from(byValue, ([value, replacement]) => ({ value, replacement }))
+ .sort((left, right) => {
+ const byLength = right.value.length - left.value.length;
+ if (byLength !== 0) return byLength;
+ return Number(right.replacement === '<identity-agent>')
+ - Number(left.replacement === '<identity-agent>');
+ });
+}
diff --git a/packages/maker-remote-ssh/src/types.ts b/packages/maker-remote-ssh/src/types.ts
index ec9ef4c916..2401addf65 100644
--- a/packages/maker-remote-ssh/src/types.ts
+++ b/packages/maker-remote-ssh/src/types.ts
@@ -16,27 +16,60 @@ export type RemoteStatus =
export type AuthMethod = 'agent' | 'key';
/**
- * Source of truth for a host entry. `ssh-config` = parsed from
- * `~/.ssh/config`; `manual` = added via maker UI (also written back to
- * `~/.ssh/config` so terminal `ssh <alias>` keeps working).
+ * `manual` remains only for older in-memory fixtures. Hosts hydrated from
+ * disk always use `ssh-config`; ownership is represented independently by
+ * `managedByCindy`.
*/
export type HostSource = 'ssh-config' | 'manual';
+/**
+ * Effective OpenSSH authentication metadata consumed by Cindy's agent path.
+ *
+ * `identityFile` on HostConfig remains reserved for an explicit Cindy marker:
+ * a private key for `auth=key`, or an explicit agent pin for `auth=agent`.
+ * Ordinary OpenSSH IdentityFile entries live here so an external host can be
+ * Agent-first without accidentally reading an encrypted private key or
+ * guessing a sibling `.pub` filename.
+ */
+export interface SshAuthenticationMetadata {
+ /** Marker from the first concrete Host declaration, if Cindy wrote one. */
+ marker?: AuthMethod;
+ /** Effective first-value-wins IdentitiesOnly value. */
+ identitiesOnly: boolean;
+ /** Effective first-value-wins IdentityAgent token, before endpoint expansion. */
+ identityAgent?: string;
+ /** Effective explicit/default identity paths, excluding the `none` sentinel. */
+ configuredIdentityFiles: string[];
+ /** True when any matching IdentityFile directive appeared, including `none`. */
+ identityFileDirectiveSeen: boolean;
+ /** True when a matching case-insensitive IdentityFile `none` sentinel appeared. */
+ identityFileNoneSeen: boolean;
+ /** Ordered, de-duplicated public-key fingerprints used to filter ssh-agent. */
+ allowedAgentFingerprints?: string[];
+ /** Cindy subset limitation. Kept on the host so LIST succeeds; CONNECT fails. */
+ unsupportedReason?: string;
+}
+
/**
* One remote machine known to maker. `id` doubles as the SSH alias
- * (the `Host <id>` line in ~/.ssh/config) — they must match so that
- * round-tripping through the config file is lossless.
+ * (the concrete `Host <id>` declaration discovered from OpenSSH config).
*/
export interface HostConfig {
- /** alias / unique key. Also the `Host` directive in ~/.ssh/config. */
+ /** alias / unique key. Also the concrete OpenSSH `Host` name. */
id: string;
+ /** Desktop may project a local preference here; never participates in SSH lookup. */
+ displayName?: string;
hostname: string;
port: number;
user: string;
authMethod: AuthMethod;
- /** absolute path; only meaningful when authMethod === 'key'. */
+ /** Absolute key path; direct key for `key`, optional agent pin for `agent`. */
identityFile?: string;
+ /** Effective OpenSSH agent metadata; never overloaded as a private-key path. */
+ sshAuthentication?: SshAuthenticationMetadata;
source: HostSource;
+ /** True only for a unique single-alias block in Cindy's managed SSH file. */
+ managedByCindy: boolean;
}
/** Snapshot of a host's runtime state for renderer. */