DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(ssh): vendor dsh-tauri-ssh(+ui) as built-in plugins with CSS Modules build fix
Menghuan1918263890e0c280
diff --git a/archive/docs/plugins/ssh-cordis.patch.example.md b/archive/docs/plugins/ssh-cordis.patch.example.mdnew file mode 100644index 00000000..3523836b--- /dev/null+++ b/archive/docs/plugins/ssh-cordis.patch.example.md@@ -0,0 +1,111 @@+# dsh-remote 插件安装补丁(cordis.patch.yml 示例)++> 本文档自 dsh-tauri-plugins 仓库随插件源码迁入,描述把 `dsh-tauri-ssh`(+`-ui`)+> 手工装进**独立 DSH 检出 / 运行中的 DSH 实例**的补丁写法。在桌面仓库内这两包+> 已是内置插件(`packages/dsh-tauri-ssh`、`packages/dsh-tauri-ssh-ui`),随+> `build:plugins` 打包、由 internal 机制自动装载,无需按下文手工接线;下文仅+> 在脱离桌面仓库单独分发插件时需要。++把下面的 `- insert:` 块追加到 DSH 检出的+`packages/bundle/web-app/cordis.patch.yml`(文件末尾即可,追加多个+`- insert:` 块是合法的)。`ssh-remote` 是宿主内核(设置命名空间 ++同源 `/api-ssh` 连接面,连接与机器发现都读本机 `~/.ssh`),`ui-ssh` 是+设置页(`dsh.client` 行,浏览器半边由 `client-modules` 节点半边扫描进+`window.__DSH_BOOT__` 并按 `/plugins/ui-ssh/client.js` 提供)。++```yaml+# ── dsh-remote:SSH 远程机器 ──────────────────────────────────────────────++- insert:+ # 连接内核:settings 命名空间 + 同源 /api-ssh 路由(依赖 base 层的+ # settings 与 webServer 服务)。config 全部可省略,省略时使用 schema 默认值。+ - id: ssh-remote+ name: dsh-tauri-ssh+ config:+ connectTimeoutMs: 15000+ healthCheckTimeoutMs: 3000+ healthPollIntervalMs: 1000+ healthPollAttempts: 30+ # sshDir: '~/.ssh' # 可选:凭据目录覆盖(config 与身份文件所在)+ # remotePort: 3080 # 可选:未覆盖机器的默认远端 dsh web 端口+ # startCommand: '$HOME/.local/bin/dsh web --host 127.0.0.1 --port {port}'+ # # 可选:默认启动命令模板({port} 替换);远端 PATH 无 dsh 时填绝对路径+ # installRepo: 'https://git.example.com/team/dsh.git'+ # # 可选:一键安装克隆的 git 仓库(远端执行 clone,需远端可访问;+ # # 官方 deepseek-harness 仓库尚未创建,请填你自己的仓库地址)+ # installRef: 'main'+ # # 可选:一键安装检出的分支/tag(默认仓库默认分支)+ # installTimeoutMs: 1800000 # 可选:一次远端安装的截止时间(毫秒)++ # 设置页:浏览器插件注册表行(dsh.client 声明在包内 package.json)。+ - id: ui-ssh+ name: dsh-tauri-ssh-ui+```++注意:`ssh-remote` 行依赖 `settings`/`webServer`,它们由 base 补丁的行提供;+`ui-ssh` 行依赖 `slots`/`locale`,由 web-app 补丁的行提供 ——+两个插件都放在 web-app 补丁里即可(web-app 覆盖 base)。++> **关键**:新插件的行**必须**写在 `- insert:` 块里。只写 `- id: x` 的裸行+> 只对**已存在**的 id 生效(覆盖配置);id 不存在时 loader 会静默丢弃该行+> (实测确认)。++### 方式 B:运行中的 DSH 安装(零源码改动,推荐个人环境)++不需要动 DSH 检出 —— 和已有的 `dsh-better-sidebar` 一样,通过 profile 安装:++1. 把两个包放到任意目录(例如本仓库 `packages/` 下);+2. `~/.dsh/profiles/web/package.json` 的 `dependencies` 增加两条 `link:` 依赖:+```json+{+ "dsh-tauri-ssh": "link:<desktop-repo>/packages/dsh-tauri-ssh",+ "dsh-tauri-ssh-ui": "link:<desktop-repo>/packages/dsh-tauri-ssh-ui"+}+```+3. `~/.dsh/profiles/web/cordis.patch.yml` 追加:+```yaml+- insert:+ - id: ssh-remote+ name: dsh-tauri-ssh+ - id: ui-ssh+ name: dsh-tauri-ssh-ui+```+4. `cd ~/.dsh/profiles/web && pnpm install`;+5. 构建插件产物(`dist/`):在本仓库运行+ `pnpm --filter dsh-tauri-ssh --filter dsh-tauri-ssh-ui run build`;+6. `dsh web` → 设置 → SSH 机器。++> 版本要求:`dsh-tauri-ssh-ui` 的 `dsh.client.inject` 面向+> **dsh ≥ 0.1.2-alpha.1**(`slots` 服务由 `dsh-client-ui-renderer` 提供)。+> 更早版本(≤ 0.1.1-rc.2)需把该行换回 `@deepseek-ai/dsh-client-runtime`。++同时需要:++1. **包位置**:把 `packages/dsh-tauri-ssh` 复制为+ `<dsh>/packages/host/dsh-tauri-ssh`,把 `packages/dsh-tauri-ssh-ui` 复制为+ `<dsh>/packages/client/dsh-tauri-ssh-ui`。工作区 glob `packages/*/*` 会自动收录。++2. **pnpm-workspace.yaml**:在 DSH 检出的 `pnpm-workspace.yaml` 的+ `allowBuilds:` 里追加两行(ssh2 的安装脚本在纯 JS 回退下不需要执行):++ ```yaml+ allowBuilds:+ ssh2: false+ cpu-features: false+ ```++3. **类型检查接线**(`tsc -b` 构建顺序):+ - `tsconfig.host.json` 的 `references` 数组追加+ `{ "path": "./packages/host/dsh-tauri-ssh" }`;+ - `tsconfig.client.json` 的 `references` 数组追加+ `{ "path": "./packages/client/dsh-tauri-ssh-ui" }`。++4. 构建并启动:++ ```bash+ pnpm install+ pnpm run build:lib+ dsh web # 或 pnpm run dev:web+ ```++5. 打开 Web UI → 设置 → SSH 机器,添加机器、测试、连接、打开。diff --git a/packages/dsh-tauri-bundle/package.json b/packages/dsh-tauri-bundle/package.jsonindex a5cb167a..2765cbb7 100644--- a/packages/dsh-tauri-bundle/package.json+++ b/packages/dsh-tauri-bundle/package.json@@ -11,6 +11,8 @@"dsh-tauri-pet": "workspace:*","dsh-tauri-rightclick": "workspace:*","dsh-tauri-session": "workspace:*",+ "dsh-tauri-ssh": "workspace:*",+ "dsh-tauri-ssh-ui": "workspace:*","dsh-tauri-turnrewind": "workspace:*","dsh-tauri-ui": "workspace:*","dsh-tauri-worktree": "workspace:*"diff --git a/packages/dsh-tauri-ssh-ui/cordis.patch.yml b/packages/dsh-tauri-ssh-ui/cordis.patch.ymlnew file mode 100644index 00000000..2439cd4b--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/cordis.patch.yml@@ -0,0 +1,3 @@+- insert:+ - id: ui-ssh+ name: dsh-tauri-ssh-uidiff --git a/packages/dsh-tauri-ssh-ui/package.json b/packages/dsh-tauri-ssh-ui/package.jsonnew file mode 100644index 00000000..3dd0742e--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/package.json@@ -0,0 +1,75 @@+{+ "name": "dsh-tauri-ssh-ui",+ "type": "module",+ "version": "0.6.7",+ "description": "DSH remote-machine client plugin: the Settings page for SSH machines (CRUD through the settings API, connect/test/disconnect and Open through the plugin's /api-ssh route)",+ "author": "Hairyf <[email protected]>",+ "license": "MIT",+ "homepage": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-ssh-ui",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/dsh-tauri-desk/deepseek-harness-desktop.git"+ },+ "bugs": {+ "url": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/issues"+ },+ "keywords": [+ "dsh",+ "plugin",+ "dsh-plugin",+ "ssh",+ "settings",+ "tauri",+ "deepseek-harness"+ ],+ "sideEffects": false,+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ },+ "./client": "./dist/client.cjs",+ "./package.json": "./package.json"+ },+ "main": "./dist/index.js",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "files": [+ "cordis.patch.yml",+ "dist"+ ],+ "dsh": {+ "client": {+ "inject": [+ "@deepseek-ai/dsh-client-ui-renderer",+ "@deepseek-ai/dsh-client-ui-settings",+ "@deepseek-ai/dsh-client-locale"+ ],+ "platform": "web"+ },+ "bundle": {+ "patch": "./cordis.patch.yml"+ }+ },+ "scripts": {+ "build": "tsdown",+ "dev": "tsdown --watch",+ "prepublishOnly": "nr build",+ "test": "vitest run",+ "typecheck": "tsc"+ },+ "devDependencies": {+ "@testing-library/dom": "catalog:testing",+ "@testing-library/react": "catalog:testing",+ "@types/node": "catalog:types",+ "@types/react": "catalog:types",+ "@types/react-dom": "catalog:types",+ "dsh-tauri-tsdown": "workspace:*",+ "jsdom": "catalog:testing",+ "react": "catalog:runtime",+ "react-dom": "catalog:runtime",+ "tsdown": "catalog:cli",+ "typescript": "catalog:cli",+ "vitest": "catalog:testing"+ }+}diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.module.css b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.module.cssnew file mode 100644index 00000000..bfbb127f--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.module.css@@ -0,0 +1,479 @@+/* SSH-machines settings section, in the DSH settings-panel design language+ * (the vocabulary of ModelsSection.module.css): 14/22 body, 12/18 caption,+ * capsule controls (h36 r18; h28 r14 where a row is dense), 32px fields,+ * hairline `border-l2` cards. Every color resolves through a `--dsw-alias-*`+ * token, so light and dark themes both work without literals. */++.section {+ display: flex;+ flex-direction: column;+ gap: 12px;+ max-width: 760px;+ color: var(--dsw-alias-label-primary);+}++.title {+ margin: 0;+ font-size: 18px;+ line-height: 28px;+ font-weight: 600;+ color: var(--dsw-alias-label-primary);+}++.intro {+ margin: 0;+ font-size: 13px;+ line-height: 20px;+ color: var(--dsw-alias-label-tertiary);+}++/* The page chrome: refresh / add / save. */+.chrome {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+}++/* Capsule button base (Button primitive geometry). */+.button {+ box-sizing: border-box;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 4px;+ height: 36px;+ padding: 0 14px;+ border: none;+ border-radius: 18px;+ background: transparent;+ color: var(--dsw-alias-label-primary);+ font: inherit;+ font-size: 14px;+ line-height: 22px;+ cursor: pointer;+}++.button:disabled {+ cursor: default;+ opacity: 0.4;+}++/* Dense capsule for row actions. */+.sm {+ height: 28px;+ padding: 0 10px;+ border-radius: 14px;+ font-size: 12px;+ line-height: 18px;+}++.primary {+ background: var(--dsw-alias-button-primary-fill);+ color: var(--dsw-alias-label-primary-foreground);+}++.primary:hover:not(:disabled) {+ background: var(--dsw-alias-button-primary-hover);+}++.secondary {+ border: 1px solid var(--dsw-alias-border-l2);+ background: transparent;+}++.secondary:hover:not(:disabled) {+ background: var(--dsw-alias-interactive-bg-hover);+}++.danger {+ color: var(--dsw-alias-state-error-primary);+}++.danger:hover:not(:disabled) {+ background: var(--dsw-alias-interactive-bg-hover-danger);+}++/* "Add machine": a dashed place, like every other empty-list affordance. */+.add {+ border: 1px dashed var(--dsw-alias-border-l3);+ background: transparent;+}++.add:hover:not(:disabled) {+ background: var(--dsw-alias-interactive-bg-hover);+}++/* The machine list: one hairline card per machine. */+.rows {+ list-style: none;+ margin: 12px 0 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 8px;+}++/* The read-only ~/.ssh/config group header. */+.group {+ display: flex;+ flex-direction: column;+ gap: 2px;+ margin-top: 12px;+}++.groupTitle {+ margin: 0;+ font-size: 12px;+ line-height: 18px;+ font-weight: 500;+ color: var(--dsw-alias-label-secondary);+}++.groupHint {+ margin: 0;+ font-size: 12px;+ line-height: 18px;+ color: var(--dsw-alias-label-tertiary);+}++.rowCard {+ border: 1px solid var(--dsw-alias-border-l2);+ border-radius: 12px;+ padding: 12px 14px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ background: var(--dsw-alias-bg-layer-3);+}++.rowHead {+ display: flex;+ align-items: center;+ gap: 10px;+}++.rowIdentity {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+}++.rowName {+ font-size: 14px;+ line-height: 22px;+ font-weight: 500;+ color: var(--dsw-alias-label-primary);+}++/* The host as a pill annotation on the name (the settings badge idiom). */+.rowTag {+ flex: none;+ padding: 2px 8px;+ border: none;+ border-radius: 999px;+ background: var(--dsw-alias-bg-module-platform);+ font-size: 11px;+ line-height: 16px;+ color: var(--dsw-alias-label-secondary);+}++/* Connection state: dot (StateDot vocabulary) + caption text. */+.status {+ font-size: 12px;+ line-height: 18px;+ color: var(--dsw-alias-label-tertiary);+}++.stateDot {+ position: relative;+ display: inline-block;+ flex: none;+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: currentColor;+ color: var(--dsw-alias-label-caption);+}++.stateDot[data-state='done'] {+ color: var(--dsw-alias-state-success-primary);+}++.stateDot[data-state='ongoing'] {+ color: var(--dsw-static-deepseek-450);+ animation: dsh-ssh-pulse 1.2s var(--ds-ease-in-out) infinite;+}++.stateDot[data-state='idle']::after {+ content: '';+ position: absolute;+ inset: 25%;+ border-radius: 50%;+ background: currentColor;+}++@keyframes dsh-ssh-pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.35; }+}++/* Identity color pip next to the machine name. */+.colorPip {+ display: inline-block;+ flex: none;+ width: 10px;+ height: 10px;+ border-radius: 50%;+ box-shadow: inset 0 0 0 1px rgb(0 0 0 / 12%);+}++/* The appearance row: swatches + the tint-border switch. */+.appearance {+ display: flex;+ align-items: center;+ gap: 10px;+ flex-wrap: wrap;+}++.swatches {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ flex-wrap: wrap;+}++.swatch {+ box-sizing: border-box;+ width: 20px;+ height: 20px;+ padding: 0;+ border: 1px solid var(--dsw-alias-border-l2);+ border-radius: 50%;+ background: var(--swatch-color);+ cursor: pointer;+}++.swatch:hover {+ border-color: var(--dsw-alias-border-l4);+}++.swatch[data-selected='true'] {+ outline: 2px solid var(--dsw-alias-brand-primary);+ outline-offset: 2px;+}++/* The "default" reset swatch: hollow with a diagonal strike. */+.swatchNone {+ background: linear-gradient(+ to top right,+ transparent calc(50% - 1px),+ var(--dsw-alias-label-tertiary),+ transparent calc(50% + 1px)+ );+}++.switchRow {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ margin-left: 4px;+}++/* The hand-rolled toggle (the SubagentModelSelectionCard vocabulary). */+.switch {+ position: relative;+ width: 36px;+ height: 20px;+ padding: 0;+ border: none;+ border-radius: 10px;+ background: var(--dsw-alias-border-l3);+ cursor: pointer;+ transition: background 0.15s var(--ds-ease-in-out);+}++.switch::after {+ content: '';+ position: absolute;+ top: 2px;+ left: 2px;+ width: 16px;+ height: 16px;+ border-radius: 50%;+ background: var(--dsw-alias-bg-layer-1);+ box-shadow: 0 1px 2px rgb(0 0 0 / 20%);+ transition: transform 0.15s var(--ds-ease-in-out);+}++.switch[aria-checked='true'] {+ background: var(--dsw-alias-state-business-primary);+}++.switch[aria-checked='true']::after {+ transform: translateX(16px);+}++.switch:disabled {+ opacity: 0.4;+ cursor: default;+}++.rowActions {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ margin-left: auto;+}++/* The editing surface: a filled module on the panel. */+.editor {+ border-radius: 12px;+ background: var(--dsw-alias-bg-module-platform);+ padding: 14px 16px;+ display: flex;+ flex-direction: column;+ gap: 12px;+}++.grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));+ gap: 8px 12px;+}++.field {+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.fieldLabel {+ font-size: 12px;+ line-height: 18px;+ font-weight: 500;+ color: var(--dsw-alias-label-secondary);+}++.input {+ box-sizing: border-box;+ width: 100%;+ height: 32px;+ padding: 0 10px;+ border: 1px solid var(--dsw-alias-border-l2);+ border-radius: 8px;+ font: inherit;+ font-size: 14px;+ line-height: 22px;+ background: var(--dsw-alias-bg-layer-1);+ color: var(--dsw-alias-label-primary);+}++.input:focus {+ outline: none;+ border-color: var(--dsw-alias-brand-primary);+}++.input::placeholder {+ color: var(--dsw-alias-label-dimmed);+}++.input:disabled {+ opacity: 0.6;+ cursor: default;+}++/* Per-machine status lines. */+.statusError {+ margin: 0;+ font-size: 12px;+ line-height: 18px;+ color: var(--dsw-alias-state-error-primary);+}++.link {+ margin: 0;+ font-size: 12px;+ line-height: 18px;+ font-family: var(--ds-font-family-code);+ color: var(--dsw-alias-label-tertiary);+ overflow-wrap: anywhere;+}++/* The one-click install surface (dsh missing on the remote). */+.installBox {+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 10px 12px;+ border: 1px solid var(--dsw-alias-border-l2);+ border-radius: 8px;+ background: var(--dsw-alias-surface-tinted);+}++.installHint {+ margin: 0;+ font-size: 12px;+ line-height: 18px;+ color: var(--dsw-alias-label-secondary);+}++.installLog {+ margin: 0;+ max-height: 140px;+ overflow: auto;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ font-family: var(--ds-font-family-code);+ font-size: 11px;+ line-height: 16px;+ color: var(--dsw-alias-label-tertiary);+}++.installNote {+ margin: 0;+ font-size: 12px;+ line-height: 18px;+ color: var(--dsw-alias-label-secondary);+}++/* Page-level banners. */+.notice {+ margin: 0;+ font-size: 12px;+ line-height: 18px;+ color: var(--dsw-alias-label-secondary);+}++.error {+ margin: 0;+ font-size: 12px;+ line-height: 18px;+ color: var(--dsw-alias-state-error-primary);+}++.hint {+ margin: 0;+ font-size: 12px;+ line-height: 18px;+ color: var(--dsw-alias-label-tertiary);+}++.empty {+ margin: 0;+ padding: 12px;+ border: 1px dashed var(--dsw-alias-border-l3);+ border-radius: 8px;+ text-align: center;+ font-size: 12px;+ line-height: 18px;+ color: var(--dsw-alias-label-tertiary);+}++@media (prefers-reduced-motion: reduce) {+ .stateDot[data-state='ongoing'] {+ animation: none;+ opacity: 0.6;+ }+}diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.test.tsx b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.test.tsxnew file mode 100644index 00000000..3c4d6ba0--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.test.tsx@@ -0,0 +1,457 @@+import type { SshKey } from '../locales/index.js'+import type { FetchFn, MachineRow, SshApiResponse } from '../store/index.js'+import { fireEvent, screen, waitFor, within } from '@testing-library/dom'+import { act, cleanup, render } from '@testing-library/react'+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from 'vitest'+import { en } from '../locales/index.js'+import { MachinesStore } from '../store/index.js'+import { MachinesSection, OPEN_WINDOW_FEATURES } from './machines-section.js'++afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+})++const t = ((key: string) => (en as Record<string, string>)[key] ?? key) as (key: SshKey) => string++type FetchMock = ReturnType<typeof vi.fn<FetchFn>>++function fakeFetch(envelope: SshApiResponse): FetchMock {+ return vi.fn<FetchFn>(async () => ({ json: async () => envelope }) as unknown as Response)+}++const machineA: MachineRow = {+ id: 'a',+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ hasPassword: true,+ hasPassphrase: false,+ remotePort: 3080,+}++function mount(overrides: { envelope?: SshApiResponse } = {}) {+ const fetchFn = fakeFetch(overrides.envelope ?? { ok: true, value: { items: [] } })+ const store = new MachinesStore(fetchFn)+ const view = render(<MachinesSection store={store} t={t} />)+ return { view, store, fetchFn }+}++describe('machinesSection', () => {+ it('renders the loaded machine cards with statuses', async () => {+ const { fetchFn } = mount({+ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' }] } },+ })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ expect(screen.getByTestId('status-a').textContent).toContain('Connected')+ expect(screen.getByText('http://127.0.0.1:49152')).toBeTruthy()+ const passwordInput = screen.getByPlaceholderText('set')+ expect(passwordInput).toBeTruthy()+ expect(fetchFn).toHaveBeenCalledWith('/api-ssh', expect.objectContaining({ method: 'POST' }))+ })++ it('shows the empty state and adds a machine draft', async () => {+ mount()+ await waitFor(() => expect(screen.getByText(/No SSH machines yet/)).toBeTruthy())+ fireEvent.click(screen.getByText('Add machine'))+ expect(screen.getByTestId('machine-')).toBeTruthy()+ const idInput = screen.getByLabelText('ID')+ fireEvent.change(idInput, { target: { value: 'n1' } })+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'newton' } })+ fireEvent.change(screen.getByLabelText('Host or config alias'), { target: { value: '10.1.1.1' } })+ fireEvent.change(screen.getByLabelText('User (optional)'), { target: { value: 'ops' } })+ expect(screen.getByText('Save').closest('button')?.hasAttribute('disabled')).toBe(false)+ })++ it('blocks saving while a draft is incomplete', async () => {+ mount()+ await waitFor(() => expect(screen.getByText(/No SSH machines yet/)).toBeTruthy())+ fireEvent.click(screen.getByText('Add machine'))+ expect(screen.getByText(/Fill in the machine ID, name, and host/)).toBeTruthy()+ expect(screen.getByText('Save').closest('button')?.hasAttribute('disabled')).toBe(true)+ })++ it('persists edits through the store', async () => {+ const { fetchFn } = mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } } })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'alpha-2' } })+ fireEvent.change(screen.getByLabelText('Password (optional)'), { target: { value: 'sekrit' } })+ fireEvent.click(screen.getByText('Save'))+ await waitFor(() => expect(saveCalls(fetchFn)).toHaveLength(1))+ const payload = saveCalls(fetchFn)[0] as { row: Record<string, unknown>, secrets?: Record<string, unknown> }+ expect(payload.row).toMatchObject({ name: 'alpha-2' })+ expect(payload.secrets).toMatchObject({ password: 'sekrit' })+ })++ it('removes a draft and removes the machine on save', async () => {+ const { fetchFn } = mount({+ envelope: {+ ok: true,+ value: { items: [{ ...machineA, state: 'disconnected' }, { ...machineA, id: 'b', name: 'beta', state: 'disconnected' }] },+ },+ })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ const betaCard = screen.getByTestId('machine-b')+ fireEvent.click(withinButton(betaCard, 'Remove'))+ fireEvent.click(screen.getByText('Save'))+ await waitFor(() => expect(removeCalls(fetchFn)).toHaveLength(1))+ expect(removeCalls(fetchFn)[0]).toEqual({ method: 'machine.remove', payload: { machineId: 'b' } })+ })++ it('tests, connects, opens, and disconnects a machine', async () => {+ const fetchFn = fakeFetch({ ok: true, value: { items: [] } })+ const store = new MachinesStore(fetchFn)+ store.store.update((state) => {+ state.status = 'ready'+ state.machines = [machineA]+ })+ const openSpy = vi.spyOn(window, 'open').mockReturnValue(null)+ render(<MachinesSection store={store} t={t} />)+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())++ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: true, banner: 'Linux alpha' } }) } as unknown as Response)+ fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Test'))+ await waitFor(() => expect(screen.getByTestId('notice').textContent).toContain('Linux alpha'))++ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:49152' } }) } as unknown as Response)+ fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Connect'))+ await waitFor(() => expect(withinButton(screen.getByTestId('machine-a'), 'Open')).toBeTruthy())+ fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Open'))+ expect(openSpy).toHaveBeenCalledWith('http://127.0.0.1:49152', '_blank', OPEN_WINDOW_FEATURES)++ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: {} }) } as unknown as Response)+ fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Disconnect'))+ await waitFor(() => expect(withinButton(screen.getByTestId('machine-a'), 'Connect')).toBeTruthy())+ })++ it('renders the connecting state with the connect action disabled', async () => {+ mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting' }] } } })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ expect(screen.getByTestId('status-a').textContent).toContain('Connecting')+ expect(withinButton(screen.getByTestId('machine-a'), 'Connect').hasAttribute('disabled')).toBe(true)+ })++ it('edits every config field and falls back on malformed numbers', async () => {+ const { fetchFn } = mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } } })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ fireEvent.change(screen.getByLabelText('Port'), { target: { value: '2222' } })+ fireEvent.change(screen.getByLabelText('Remote port'), { target: { value: 'abc' } })+ fireEvent.change(screen.getByLabelText('Start command (optional)'), { target: { value: 'dsh web --port 3000' } })+ fireEvent.change(screen.getByLabelText('Key passphrase (optional)'), { target: { value: 'phrase' } })+ fireEvent.click(screen.getByText('Save'))+ await waitFor(() => expect(saveCalls(fetchFn)).toHaveLength(1))+ const payload = saveCalls(fetchFn)[0] as { row: Record<string, unknown>, secrets?: Record<string, unknown> }+ expect(payload.row).toMatchObject({+ port: 2222,+ remotePort: 3080,+ startCommand: 'dsh web --port 3000',+ })+ expect(payload.secrets).toMatchObject({ passphrase: 'phrase' })+ })++ it('opens nothing when a connected machine has no tunnel url', async () => {+ mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected' }] } } })+ const openSpy = vi.spyOn(window, 'open').mockReturnValue(null)+ await waitFor(() => expect(withinButton(screen.getByTestId('machine-a'), 'Open')).toBeTruthy())+ fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Open'))+ expect(openSpy).not.toHaveBeenCalled()+ })++ it('persists the identity color and the border tint switch', async () => {+ const { fetchFn } = mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } } })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ fireEvent.click(screen.getByLabelText('Color: #4176E6'))+ const card = screen.getByTestId('machine-a')+ expect(card.style.borderColor).toBe('')+ fireEvent.click(within(card).getByRole('switch'))+ expect(card.style.borderColor).toBe('rgb(65, 118, 230)')+ fireEvent.click(screen.getByText('Save'))+ await waitFor(() => expect(saveCalls(fetchFn)).toHaveLength(1))+ expect((saveCalls(fetchFn)[0] as { row: Record<string, unknown> }).row)+ .toMatchObject({ color: '#4176E6', tintBorder: true })+ })++ it('resets color and border tint through the default swatch', async () => {+ const { fetchFn } = mount({+ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected', color: '#4176E6', tintBorder: true }] } },+ })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ expect(screen.getByTestId('machine-a').style.borderColor).toBe('rgb(65, 118, 230)')+ fireEvent.click(screen.getByLabelText('Default'))+ fireEvent.click(screen.getByText('Save'))+ await waitFor(() => expect(saveCalls(fetchFn)).toHaveLength(1))+ const row = (saveCalls(fetchFn)[0] as { row: Record<string, unknown> }).row+ expect(row.color).toBeUndefined()+ expect(row.tintBorder).toBeUndefined()+ })++ it('shows the live progress text of an in-flight operation', async () => {+ mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } }] } } })+ await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Health check 2/30'))+ })++ it('shows the handshake progress phase', async () => {+ mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'handshake' } }] } } })+ await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Connecting over SSH'))+ })++ it('falls back to question marks when probing progress has no numbers', async () => {+ mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'probing' } }] } } })+ await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Health check ?/?'))+ })++ it('shows the starting progress phase', async () => {+ mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'starting' } }] } } })+ await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Starting the remote instance'))+ })++ it('polls the host while an operation is in flight and stops when idle', async () => {+ vi.useFakeTimers()+ try {+ const fetchFn = fakeFetch({ ok: true, value: { items: [] } })+ const store = new MachinesStore(fetchFn)+ store.store.update((state) => {+ state.status = 'ready'+ state.machines = [machineA]+ state.statuses = { a: { state: 'connecting', progress: { phase: 'handshake' } } }+ })+ render(<MachinesSection store={store} t={t} />)+ const before = fetchFn.mock.calls.length+ await act(async () => vi.advanceTimersByTime(1600))+ expect(fetchFn.mock.calls.length).toBe(before + 1)+ // Idle machines stop the polling loop.+ store.store.update((state) => {+ state.statuses = { a: { state: 'disconnected' } }+ state.busy = {}+ })+ await act(async () => vi.advanceTimersByTime(3200))+ expect(fetchFn.mock.calls.length).toBe(before + 1)+ }+ finally {+ vi.useRealTimers()+ }+ })++ it('shows per-machine failures and the page error banner', async () => {+ const { store } = mount({+ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected', lastError: 'auth failed' }] } },+ })+ await waitFor(() => expect(screen.getByText('auth failed')).toBeTruthy())+ store.store.update((state) => {+ state.error = 'boom'+ })+ await waitFor(() => expect(screen.getByText(/Error: boom/)).toBeTruthy())+ })++ it('renders discovered config aliases as read-only cards with working actions', async () => {+ const fetchFn = fakeFetch({+ ok: true,+ value: {+ items: [],+ discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: 'root', hasPassword: false, state: 'disconnected' }],+ },+ })+ const store = new MachinesStore(fetchFn)+ render(<MachinesSection store={store} t={t} />)+ await waitFor(() => expect(screen.getByText('dev')).toBeTruthy())+ expect(screen.getByText('Hosts from ~/.ssh/config')).toBeTruthy()+ const card = screen.getByTestId('machine-dev')+ // Read-only: no editable fields, no Remove button.+ expect(within(card).queryByLabelText('ID')).toBeNull()+ expect(within(card).queryByText('Remove')).toBeNull()+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: true, banner: 'Linux dev' } }) } as unknown as Response)+ fireEvent.click(withinButton(card, 'Test'))+ await waitFor(() => expect(screen.getByTestId('notice').textContent).toContain('Linux dev'))+ })++ it('connects and opens a discovered config alias', async () => {+ const fetchFn = fakeFetch({+ ok: true,+ value: {+ items: [],+ discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'disconnected' }],+ },+ })+ const store = new MachinesStore(fetchFn)+ const openSpy = vi.spyOn(window, 'open').mockReturnValue(null)+ render(<MachinesSection store={store} t={t} />)+ await waitFor(() => expect(screen.getByText('dev')).toBeTruthy())+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:49152' } }) } as unknown as Response)+ fireEvent.click(withinButton(screen.getByTestId('machine-dev'), 'Connect'))+ await waitFor(() => expect(withinButton(screen.getByTestId('machine-dev'), 'Open')).toBeTruthy())+ fireEvent.click(withinButton(screen.getByTestId('machine-dev'), 'Open'))+ expect(openSpy).toHaveBeenCalledWith('http://127.0.0.1:49152', '_blank', OPEN_WINDOW_FEATURES)+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: {} }) } as unknown as Response)+ fireEvent.click(withinButton(screen.getByTestId('machine-dev'), 'Disconnect'))+ await waitFor(() => expect(withinButton(screen.getByTestId('machine-dev'), 'Connect')).toBeTruthy())+ })++ it('opens nothing for a discovered card without a tunnel url', async () => {+ mount({ envelope: { ok: true, value: { discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'connected' }] } } })+ const openSpy = vi.spyOn(window, 'open').mockReturnValue(null)+ await waitFor(() => expect(withinButton(screen.getByTestId('machine-dev'), 'Open')).toBeTruthy())+ fireEvent.click(withinButton(screen.getByTestId('machine-dev'), 'Open'))+ expect(openSpy).not.toHaveBeenCalled()+ })++ it('disables connect while a discovered alias is connecting', async () => {+ mount({ envelope: { ok: true, value: { discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'connecting' }] } } })+ await waitFor(() => expect(screen.getByTestId('status-dev').textContent).toContain('Connecting'))+ expect(withinButton(screen.getByTestId('machine-dev'), 'Connect').hasAttribute('disabled')).toBe(true)+ })++ it('shows a discovered alias failure inline', async () => {+ mount({ envelope: { ok: true, value: { discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'disconnected', lastError: 'auth failed' }] } } })+ await waitFor(() => expect(screen.getByText('auth failed')).toBeTruthy())+ })++ it('shows the empty state only when no manual or discovered machines exist', async () => {+ mount({ envelope: { ok: true, value: { discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', state: 'disconnected' }] } } })+ await waitFor(() => expect(screen.getByText('dev')).toBeTruthy())+ expect(screen.queryByText(/No SSH machines yet/)).toBeNull()+ })++ it('refreshes on demand', async () => {+ const { store } = mount()+ await waitFor(() => expect(screen.getByText(/No SSH machines yet/)).toBeTruthy())+ const load = vi.spyOn(store, 'load').mockResolvedValue(undefined)+ fireEvent.click(screen.getByText('Refresh'))+ expect(load).toHaveBeenCalled()+ })++ it('shows the one-click install surface when dsh is missing and installs on click', async () => {+ const { fetchFn } = mount({+ envelope: {+ ok: true,+ value: { items: [{ ...machineA, state: 'disconnected', lastError: 'dsh is not installed', dshMissing: true }] },+ },+ })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ expect(screen.getByText(/No dsh found on the remote/)).toBeTruthy()+ expect(screen.getByText('Install dsh')).toBeTruthy()+ fireEvent.click(screen.getByText('Install dsh'))+ await waitFor(() => {+ expect(fetchFn.mock.calls.some(([_url, init]) =>+ String(init.body).includes('machine.install'))).toBe(true)+ })+ })++ it('shows the installing phase with the live streaming log', async () => {+ const { store } = mount({+ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } },+ })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ act(() => {+ store.store.update((state) => {+ state.busy.a = 'install'+ state.statuses.a = {+ state: 'disconnected',+ dshMissing: true,+ progress: { phase: 'installing', log: '==> Checking dependencies\ngit ... ok' },+ }+ })+ })+ expect(screen.getAllByText(/Installing dsh/).length).toBeGreaterThan(0)+ const log = screen.getByTestId('install-log')+ expect(log.textContent).toContain('==> Checking dependencies')+ expect(log.textContent).toContain('git ... ok')+ })++ it('shows the install outcome note under the card', async () => {+ const { store } = mount({+ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] } },+ })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ act(() => {+ store.store.update((state) => {+ state.installResults.a = { dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true }+ })+ })+ expect(screen.getByTestId('install-note-a').textContent).toContain('API key was copied')+ })++ it('shows the install note when no local key exists', async () => {+ const { store } = mount({+ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } },+ })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ act(() => {+ store.store.update((state) => {+ state.installResults.a = { dshPath: '/home/root/.local/bin/dsh', credentialsCopied: false }+ })+ })+ expect(screen.getByTestId('install-note-a').textContent).toContain('No DEEPSEEK_API_KEY found locally')+ })++ it('shows the install note with a credentials copy failure', async () => {+ const { store } = mount({+ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } },+ })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ act(() => {+ store.store.update((state) => {+ state.installResults.a = {+ dshPath: '/home/root/.local/bin/dsh',+ credentialsCopied: false,+ credentialsError: 'disk full',+ }+ })+ })+ expect(screen.getByTestId('install-note-a').textContent).toContain('disk full')+ })++ it('offers the one-click install on a discovered alias too', async () => {+ const { fetchFn } = mount({+ envelope: {+ ok: true,+ value: {+ discovered: [{+ id: 'dev',+ name: 'dev',+ host: 'dev',+ port: 22,+ user: 'root',+ hasPassword: false,+ hasPassphrase: false,+ remotePort: 3080,+ state: 'disconnected',+ dshMissing: true,+ lastError: 'dsh is not installed',+ }],+ },+ },+ })+ await waitFor(() => expect(screen.getByText('dev')).toBeTruthy())+ expect(screen.getByText(/No dsh found on the remote/)).toBeTruthy()+ fireEvent.click(screen.getByText('Install dsh'))+ await waitFor(() => {+ expect(fetchFn.mock.calls.some(([_url, init]) =>+ String(init.body).includes('machine.install'))).toBe(true)+ })+ })+})++/** The machine.save request bodies the fake fetch received. */+function saveCalls(fetchFn: ReturnType<typeof vi.fn>): unknown[] {+ return fetchFn.mock.calls+ .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload: unknown })+ .filter(call => call.method === 'machine.save')+ .map(call => call.payload)+}++/** The machine.remove request bodies the fake fetch received. */+function removeCalls(fetchFn: ReturnType<typeof vi.fn>): Array<{ method: string, payload: Record<string, unknown> }> {+ return fetchFn.mock.calls+ .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload: Record<string, unknown> })+ .filter(call => call.method === 'machine.remove')+}++/** Find one button by its accessible text inside a container. */+function withinButton(container: HTMLElement, text: string): HTMLButtonElement {+ const button = [...container.querySelectorAll('button')].find(candidate => candidate.textContent === text)+ if (button === undefined)+ throw new Error(`no button "${text}"`)+ return button as HTMLButtonElement+}diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.tsx b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.tsxnew file mode 100644index 00000000..0f1f3e59--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.tsx@@ -0,0 +1,690 @@+'use no memo'++/**+ * The SSH-machines settings section, in the DSH settings design language+ * (see packages/client/ui-models ModelsSection.module.css): token-resolved+ * colors, 32px fields, capsule controls, hairline row cards. One card per+ * machine with the config form (secrets write-only), the connection plane+ * (test/connect/open/disconnect), and the save/refresh chrome. All state+ * lives in the injected {@link MachinesStore}; the component is a thin+ * renderer over its snapshot.+ * @module dsh-tauri-ssh-ui/client/components/machines-section+ */++import type { CSSProperties, ReactNode } from 'react'+import type { SshKey } from '../locales/index.js'+import type { InstallResult, MachineRow, MachinesStore, MachineStatus, SecretValues } from '../store/index.js'+import { useEffect, useState, useSyncExternalStore } from 'react'+import css from './machines-section.module.css'++/** Registrant-owned dependencies of the section. */+export interface MachinesSectionInjected {+ store: MachinesStore+}++/** Full section props: the framework `t` seat plus the injected store. */+export interface MachinesSectionProps extends MachinesSectionInjected {+ t: (key: SshKey) => string+}++/** One editable draft row (a `new-…` key marks an unsaved machine). */+interface Draft {+ key: string+ row: MachineRow+}++/** The dirty-secret map the form carries: machine key → typed secret values. */+type DirtySecrets = Record<string, SecretValues>++/** A secret field name. */+export type SecretFieldName = 'password' | 'passphrase'++/** The connection-state dot data attribute (the StateDot vocabulary). */+type DotState = 'done' | 'ongoing' | 'idle'++const DEFAULT_PORT = 22+const DEFAULT_REMOTE_PORT = 3080++/** window.open features for the Open action: a real popup window, not a tab. */+export const OPEN_WINDOW_FEATURES = 'width=1280,height=860,noopener'++/** The identity-color palette (fits the DSH status hue family). */+const COLOR_CHOICES = [+ '#4176E6',+ '#0EA5E9',+ '#14B8A6',+ '#22C55E',+ '#F59E0B',+ '#F97316',+ '#EF4444',+ '#A855F7',+]++/** One machine's editable config card. */+export function MachineCard(+ { draft, t, secretSet, status, busy, dirty, onChange, onSecret, onRemove, onTest, onConnect, onDisconnect, onOpen, onInstall, installResult }: {+ draft: Draft+ t: (key: SshKey) => string+ secretSet: Record<string, boolean>+ status: MachineStatus | undefined+ busy: 'test' | 'connect' | 'disconnect' | 'install' | undefined+ dirty: SecretValues+ onChange: (key: string, patch: Partial<MachineRow>) => void+ onSecret: (key: string, field: SecretFieldName, value: string) => void+ onRemove: (key: string) => void+ onTest: (id: string) => void+ onConnect: (id: string) => void+ onDisconnect: (id: string) => void+ onOpen: (id: string) => void+ onInstall: (id: string) => void+ installResult: InstallResult | undefined+ },+): ReactNode {+ const { row } = draft+ const connected = status?.state === 'connected'+ const connecting = status?.state === 'connecting'+ const id = row.id+ const color = colorOf(row)+ return (+ <li+ className={css.rowCard}+ data-testid={`machine-${id}`}+ style={row.tintBorder === true && color !== undefined ? { borderColor: color } : undefined}+ >+ <div className={css.rowHead}>+ <span className={css.rowIdentity}>+ <span className={css.stateDot} data-state={dotStateOf(status)} aria-hidden="true" />+ {color !== undefined+ ? <span className={css.colorPip} style={{ background: color }} aria-hidden="true" />+ : null}+ <span className={css.rowName}>{row.name === '' ? row.id : row.name}</span>+ <span className={css.rowTag}>{row.host}</span>+ <span className={css.status} data-testid={`status-${id}`}>{statusTextOf(status, t)}</span>+ </span>+ <span className={css.rowActions}>+ <button+ type="button"+ className={`${css.button} ${css.secondary} ${css.sm}`}+ disabled={busy !== undefined || connecting}+ onClick={() => onTest(id)}+ >+ {t('test')}+ </button>+ {connected+ ? (+ <>+ <button+ type="button"+ className={`${css.button} ${css.primary} ${css.sm}`}+ disabled={busy !== undefined}+ title={t('open.tip')}+ onClick={() => onOpen(id)}+ >+ {t('open')}+ </button>+ <button+ type="button"+ className={`${css.button} ${css.secondary} ${css.sm}`}+ disabled={busy !== undefined}+ onClick={() => onDisconnect(id)}+ >+ {t('disconnect')}+ </button>+ </>+ )+ : (+ <button+ type="button"+ className={`${css.button} ${css.primary} ${css.sm}`}+ disabled={busy !== undefined || connecting}+ onClick={() => onConnect(id)}+ >+ {t('connect')}+ </button>+ )}+ <button+ type="button"+ className={`${css.button} ${css.danger} ${css.sm}`}+ disabled={busy !== undefined}+ onClick={() => onRemove(draft.key)}+ >+ {t('remove')}+ </button>+ </span>+ </div>+ <div className={css.editor}>+ <div className={css.grid}>+ <Field label={t('field.id')}>+ <input+ className={css.input}+ value={row.id}+ disabled={!draft.key.startsWith('new-')}+ onChange={event => onChange(draft.key, { id: event.target.value })}+ />+ </Field>+ <Field label={t('field.name')}>+ <input+ className={css.input}+ value={row.name}+ onChange={event => onChange(draft.key, { name: event.target.value })}+ />+ </Field>+ <Field label={t('field.host')}>+ <input+ className={css.input}+ value={row.host}+ onChange={event => onChange(draft.key, { host: event.target.value })}+ />+ </Field>+ <Field label={t('field.port')}>+ <input+ className={css.input}+ type="number"+ value={row.port}+ onChange={event => onChange(draft.key, { port: numberOf(event.target.value, DEFAULT_PORT) })}+ />+ </Field>+ <Field label={t('field.user')}>+ <input+ className={css.input}+ value={row.user}+ onChange={event => onChange(draft.key, { user: event.target.value })}+ />+ </Field>+ <Field label={t('field.remotePort')}>+ <input+ className={css.input}+ type="number"+ value={row.remotePort}+ onChange={event => onChange(draft.key, { remotePort: numberOf(event.target.value, DEFAULT_REMOTE_PORT) })}+ />+ </Field>+ <Field label={t('field.startCommand')}>+ <input+ className={css.input}+ value={row.startCommand ?? ''}+ onChange={event => onChange(draft.key, { startCommand: event.target.value })}+ />+ </Field>+ </div>+ <div className={css.grid}>+ <SecretField+ field="password"+ label={t('field.password')}+ keyName={draft.key}+ secretSet={secretSet}+ t={t}+ value={dirty.password ?? ''}+ onValue={onSecret}+ />+ <SecretField+ field="passphrase"+ label={t('field.passphrase')}+ keyName={draft.key}+ secretSet={secretSet}+ t={t}+ value={dirty.passphrase ?? ''}+ onValue={onSecret}+ />+ </div>+ <AppearanceEditor row={row} t={t} onChange={onChange} draftKey={draft.key} />+ </div>+ {status?.dshMissing === true+ ? <InstallPanel status={status} busy={busy} t={t} onInstall={() => onInstall(id)} />+ : null}+ {status?.lastError !== undefined ? <p className={css.statusError} role="alert">{status.lastError}</p> : null}+ {status?.tunnelBaseUrl !== undefined ? <p className={css.link}>{status.tunnelBaseUrl}</p> : null}+ {installResult !== undefined+ ? <p className={css.installNote} data-testid={`install-note-${id}`}>{installNoteOf(installResult, t)}</p>+ : null}+ </li>+ )+}++/**+ * One read-only machine card from ~/.ssh/config: identity, status, and the+ * connection plane only — nothing here is stored or editable.+ */+function DiscoveredCard({ row, t, status, busy, onTest, onConnect, onDisconnect, onOpen, onInstall, installResult }: {+ row: MachineRow+ t: (key: SshKey) => string+ status: MachineStatus | undefined+ busy: 'test' | 'connect' | 'disconnect' | 'install' | undefined+ onTest: (id: string) => void+ onConnect: (id: string) => void+ onDisconnect: (id: string) => void+ onOpen: (id: string) => void+ onInstall: (id: string) => void+ installResult: InstallResult | undefined+}): ReactNode {+ const connected = status?.state === 'connected'+ const connecting = status?.state === 'connecting'+ return (+ <li className={css.rowCard} data-testid={`machine-${row.id}`}>+ <div className={css.rowHead}>+ <span className={css.rowIdentity}>+ <span className={css.stateDot} data-state={dotStateOf(status)} aria-hidden="true" />+ <span className={css.rowName}>{row.name}</span>+ <span className={css.rowTag}>{t('configTag')}</span>+ <span className={css.status} data-testid={`status-${row.id}`}>{statusTextOf(status, t)}</span>+ </span>+ <span className={css.rowActions}>+ <button+ type="button"+ className={`${css.button} ${css.secondary} ${css.sm}`}+ disabled={busy !== undefined || connecting}+ onClick={() => onTest(row.id)}+ >+ {t('test')}+ </button>+ {connected+ ? (+ <>+ <button+ type="button"+ className={`${css.button} ${css.primary} ${css.sm}`}+ disabled={busy !== undefined}+ title={t('open.tip')}+ onClick={() => onOpen(row.id)}+ >+ {t('open')}+ </button>+ <button+ type="button"+ className={`${css.button} ${css.secondary} ${css.sm}`}+ disabled={busy !== undefined}+ onClick={() => onDisconnect(row.id)}+ >+ {t('disconnect')}+ </button>+ </>+ )+ : (+ <button+ type="button"+ className={`${css.button} ${css.primary} ${css.sm}`}+ disabled={busy !== undefined || connecting}+ onClick={() => onConnect(row.id)}+ >+ {t('connect')}+ </button>+ )}+ </span>+ </div>+ {status?.dshMissing === true+ ? <InstallPanel status={status} busy={busy} t={t} onInstall={() => onInstall(row.id)} />+ : null}+ {status?.lastError !== undefined ? <p className={css.statusError} role="alert">{status.lastError}</p> : null}+ {status?.tunnelBaseUrl !== undefined ? <p className={css.link}>{status.tunnelBaseUrl}</p> : null}+ {installResult !== undefined+ ? <p className={css.installNote} data-testid={`install-note-${row.id}`}>{installNoteOf(installResult, t)}</p>+ : null}+ </li>+ )+}++/** The dsh-missing install surface: a one-click install, or the live log while it runs. */+function InstallPanel({ status, busy, t, onInstall }: {+ status: MachineStatus+ busy: 'test' | 'connect' | 'disconnect' | 'install' | undefined+ t: (key: SshKey) => string+ onInstall: () => void+}): ReactNode {+ const installing = busy === 'install' || status.progress?.phase === 'installing'+ if (installing) {+ return (+ <div className={css.installBox}>+ <p className={css.installHint}>{t('progress.installing')}</p>+ <pre className={css.installLog} data-testid="install-log">{status.progress?.log ?? ''}</pre>+ </div>+ )+ }+ return (+ <div className={css.installBox}>+ <p className={css.installHint}>{t('install.hint')}</p>+ <button+ type="button"+ className={`${css.button} ${css.primary} ${css.sm}`}+ disabled={busy !== undefined}+ onClick={onInstall}+ >+ {t('install.action')}+ </button>+ </div>+ )+}++/** One operator-facing line for a finished install. */+function installNoteOf(result: InstallResult, t: (key: SshKey) => string): string {+ if (result.credentialsError !== undefined) {+ return t('install.done.error') + result.credentialsError+ }+ return result.credentialsCopied ? t('install.done.copied') : t('install.done.nokey')+}++/** One labeled field row. */+function Field({ label, children }: { label: string, children: ReactNode }): ReactNode {+ return (+ <label className={css.field}>+ <span className={css.fieldLabel}>{label}</span>+ {children}+ </label>+ )+}++/**+ * The appearance row of one machine card: an identity-color swatch set+ * (plus a "default" reset) and the tint-the-border switch, which is only+ * meaningful while a color is chosen. Clearing writes the empty-string+ * (off) form — the save path drops it.+ */+function AppearanceEditor({ row, t, onChange, draftKey }: {+ row: MachineRow+ t: (key: SshKey) => string+ onChange: (key: string, patch: Partial<MachineRow>) => void+ draftKey: string+}): ReactNode {+ const color = colorOf(row)+ return (+ <div className={css.appearance}>+ <span className={css.fieldLabel}>{t('field.color')}</span>+ <div className={css.swatches}>+ {COLOR_CHOICES.map(choice => (+ <button+ key={choice}+ type="button"+ className={css.swatch}+ data-selected={color === choice}+ style={{ '--swatch-color': choice } as CSSProperties}+ aria-label={`${t('field.color')}: ${choice}`}+ aria-pressed={color === choice}+ onClick={() => onChange(draftKey, { color: color === choice ? '' : choice })}+ />+ ))}+ <button+ type="button"+ className={`${css.swatch} ${css.swatchNone}`}+ data-selected={color === undefined}+ aria-label={t('color.none')}+ aria-pressed={color === undefined}+ title={t('color.none')}+ onClick={() => onChange(draftKey, { color: '', tintBorder: false })}+ />+ <span className={css.switchRow}>+ <button+ type="button"+ role="switch"+ aria-checked={row.tintBorder === true}+ className={css.switch}+ disabled={color === undefined}+ onClick={() => onChange(draftKey, { tintBorder: row.tintBorder !== true })}+ />+ <span className={css.fieldLabel}>{t('field.tintBorder')}</span>+ </span>+ </div>+ </div>+ )+}++/** One write-only secret input; the placeholder reports whether a value is stored. */+export function SecretField({ field, label, keyName, secretSet, t, value, onValue }: {+ field: SecretFieldName+ label: string+ keyName: string+ secretSet: Record<string, boolean>+ t: (key: SshKey) => string+ value: string+ onValue: (key: string, field: SecretFieldName, value: string) => void+}): ReactNode {+ const placeholder = secretSet[`${keyName}.${field}`] ? t('secret.set') : t('secret.unset')+ return (+ <label className={css.field}>+ <span className={css.fieldLabel}>{label}</span>+ <input+ className={css.input}+ type="password"+ value={value}+ placeholder={placeholder}+ onChange={event => onValue(keyName, field, event.target.value)}+ />+ </label>+ )+}++/** The write-only secret presence flags of one draft row, keyed like the stored sidecar. */+function secretFlagsOf(row: MachineRow): Record<string, boolean> {+ return {+ [`${row.id}.password`]: row.hasPassword,+ [`${row.id}.passphrase`]: row.hasPassphrase,+ }+}++/** The row's effective identity color ('' and undefined both mean none). */+function colorOf(row: MachineRow): string | undefined {+ return row.color === undefined || row.color === '' ? undefined : row.color+}++/** The connection-state dot color vocabulary. */+function dotStateOf(status: MachineStatus | undefined): DotState {+ if (status?.state === 'connected')+ return 'done'+ if (status?.state === 'connecting')+ return 'ongoing'+ return 'idle'+}++/** The status line: live progress text while an operation is in flight, else the state label. */+function statusTextOf(status: MachineStatus | undefined, t: (key: SshKey) => string): string {+ const progress = status?.progress+ if (progress?.phase === 'handshake')+ return t('progress.handshake')+ if (progress?.phase === 'starting')+ return t('progress.starting')+ if (progress?.phase === 'installing')+ return t('progress.installing')+ if (progress?.phase === 'probing') {+ return t('progress.probing')+ .replace('{attempt}', String(progress.attempt ?? '?'))+ .replace('{total}', String(progress.total ?? '?'))+ }+ if (status?.state === 'connected')+ return t('status.connected')+ if (status?.state === 'connecting')+ return t('status.connecting')+ return t('status.disconnected')+}++/** Parse a number input; non-numbers fall back to the default. */+function numberOf(raw: string, fallback: number): number {+ const parsed = Number(raw)+ return raw !== '' && Number.isFinite(parsed) ? parsed : fallback+}++/**+ * Render the SSH-machines settings page.+ * @returns the page element tree.+ */+export function MachinesSection({ t, store }: MachinesSectionProps): ReactNode {+ const state = useSyncExternalStore(store.subscribe, store.getSnapshot)+ const [drafts, setDrafts] = useState<Record<string, Draft>>({})+ const [dirty, setDirty] = useState<DirtySecrets>({})+ const [addCounter, setAddCounter] = useState(0)+ const [initialized, setInitialized] = useState(false)++ useEffect(() => {+ void store.load()+ }, [store])++ // While any machine has an operation in flight, poll the host every 1.5 s+ // so the live progress (handshake / starting / probing) stays current.+ const anyInFlight = Object.keys(state.busy).length > 0+ || Object.values(state.statuses).some(status => status.state === 'connecting')+ useEffect(() => {+ if (!anyInFlight)+ return+ const timer = setInterval(() => void store.poll(), 1500)+ return () => clearInterval(timer)+ }, [anyInFlight, store])++ // Initialize the draft buffer once the first load lands; later loads keep+ // the operator's in-progress edits (the buffer is the source until save).+ useEffect(() => {+ if (initialized || state.status !== 'ready')+ return+ // eslint-disable-next-line react/set-state-in-effect -- load-once hydration: the draft buffer cannot exist before the first machine.list lands, and must not reset on later loads+ setInitialized(true)+ // eslint-disable-next-line react/set-state-in-effect -- same hydrate-once guard as setInitialized above+ setDrafts(Object.fromEntries(state.machines.map(row => [row.id, { key: row.id, row: { ...row } }])))+ }, [initialized, state.status, state.machines])++ const patchDraft = (key: string, patch: Partial<MachineRow>): void => {+ setDrafts(previous => ({+ ...previous,+ [key]: { key, row: { ...previous[key]!.row, ...patch } },+ }))+ }++ const patchDirty = (key: string, field: SecretFieldName, value: string): void => {+ setDirty(previous => ({ ...previous, [key]: { ...previous[key], [field]: value } }))+ }++ const addMachine = (): void => {+ const key = `new-${addCounter}`+ setAddCounter(addCounter + 1)+ setDrafts(previous => ({+ ...previous,+ [key]: {+ key,+ row: {+ id: '',+ name: '',+ host: '',+ port: DEFAULT_PORT,+ user: '',+ hasPassword: false,+ hasPassphrase: false,+ remotePort: DEFAULT_REMOTE_PORT,+ },+ },+ }))+ }++ const removeDraft = (key: string): void => {+ setDrafts((previous) => {+ const next = { ...previous }+ delete next[key]+ return next+ })+ }++ const invalid = Object.values(drafts).some(draft =>+ draft.row.id === '' || draft.row.name === '' || draft.row.host === '')++ const save = (): void => {+ void store.persist(Object.values(drafts).map(draft => draft.row), dirty)+ }++ return (+ <div className={css.section}>+ <h2 className={css.title}>{t('title')}</h2>+ <p className={css.intro}>{t('intro')}</p>+ <div className={css.chrome}>+ <button+ type="button"+ className={`${css.button} ${css.secondary}`}+ disabled={state.status === 'loading'}+ onClick={() => void store.load()}+ >+ {t('refresh')}+ </button>+ <button+ type="button"+ className={`${css.button} ${css.add}`}+ disabled={state.status === 'loading'}+ onClick={addMachine}+ >+ {t('addMachine')}+ </button>+ <button+ type="button"+ className={`${css.button} ${css.primary}`}+ disabled={invalid || state.status === 'loading'}+ onClick={save}+ >+ {t('save')}+ </button>+ </div>+ {state.notice !== null ? <p className={css.notice} data-testid="notice">{state.notice}</p> : null}+ {state.error !== null+ ? (+ <p className={css.error} role="alert">+ {t('error.banner')}+ {state.error}+ </p>+ )+ : null}+ {invalid ? <p className={css.hint}>{t('saveHint')}</p> : null}+ {state.status === 'loading' ? <p className={css.hint}>{t('loading')}</p> : null}+ {state.status === 'ready' && Object.keys(drafts).length === 0 && state.discovered.length === 0+ ? <p className={css.empty}>{t('empty')}</p>+ : null}+ {state.discovered.length > 0+ ? (+ <>+ <div className={css.group}>+ <h3 className={css.groupTitle}>{t('configHosts')}</h3>+ <p className={css.groupHint}>{t('configHostsHint')}</p>+ </div>+ <ul className={css.rows}>+ {state.discovered.map(row => (+ <DiscoveredCard+ key={row.id}+ row={row}+ t={t}+ status={state.statuses[row.id]}+ busy={state.busy[row.id]}+ installResult={state.installResults[row.id]}+ onTest={id => void store.test(id)}+ onConnect={id => void store.connect(id)}+ onDisconnect={id => void store.disconnect(id)}+ onInstall={id => void store.install(id)}+ onOpen={(id) => {+ const tunnelBaseUrl = state.statuses[id]?.tunnelBaseUrl+ if (tunnelBaseUrl !== undefined)+ window.open(tunnelBaseUrl, '_blank', OPEN_WINDOW_FEATURES)+ }}+ />+ ))}+ </ul>+ </>+ )+ : null}+ <ul className={css.rows}>+ {Object.values(drafts).map(draft => (+ <MachineCard+ key={draft.key}+ draft={draft}+ t={t}+ secretSet={secretFlagsOf(draft.row)}+ status={state.statuses[draft.row.id]}+ busy={state.busy[draft.row.id]}+ installResult={state.installResults[draft.row.id]}+ dirty={dirty[draft.key] ?? {}}+ onChange={patchDraft}+ onSecret={patchDirty}+ onRemove={removeDraft}+ onTest={id => void store.test(id)}+ onConnect={id => void store.connect(id)}+ onDisconnect={id => void store.disconnect(id)}+ onInstall={id => void store.install(id)}+ onOpen={(id) => {+ const tunnelBaseUrl = state.statuses[id]?.tunnelBaseUrl+ if (tunnelBaseUrl !== undefined)+ window.open(tunnelBaseUrl, '_blank', OPEN_WINDOW_FEATURES)+ }}+ />+ ))}+ </ul>+ </div>+ )+}diff --git a/packages/dsh-tauri-ssh-ui/src/client/constants/index.ts b/packages/dsh-tauri-ssh-ui/src/client/constants/index.tsnew file mode 100644index 00000000..399382d4--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/constants/index.ts@@ -0,0 +1,21 @@+/**+ * Shared client constants of the SSH-machines settings page: the settings+ * slot protocol identifiers, the locale namespace, and the same-origin API+ * route the host half (`dsh-tauri-ssh`) mounts.+ * @module dsh-tauri-ssh-ui/client/constants+ */++/** Dictionary namespace owned by this plugin. */+export const SSH_LOCALE_NS = 'ssh'++/** The settings section slot this plugin registers into. */+export const SETTINGS_SECTION_SLOT = 'settings.section'++/** Registration id of this plugin's settings section (the host plugin's id). */+export const SETTINGS_SECTION_ID = 'dsh-tauri-ssh'++/** Order of this plugin's settings section among the other sections. */+export const SETTINGS_SECTION_ORDER = 50++/** The /api-ssh route the host plugin mounts (same-origin POST envelope). */+export const SSH_API_PATH = '/api-ssh'diff --git a/packages/dsh-tauri-ssh-ui/src/client/css-modules.d.ts b/packages/dsh-tauri-ssh-ui/src/client/css-modules.d.tsnew file mode 100644index 00000000..d49faa1c--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/css-modules.d.ts@@ -0,0 +1,5 @@+declare module '*.module.css' {+ /** Hashed class map compiled by the DSH client bundle preset. */+ const classes: Record<string, string>+ export default classes+}diff --git a/packages/dsh-tauri-ssh-ui/src/client/index.test.ts b/packages/dsh-tauri-ssh-ui/src/client/index.test.tsnew file mode 100644index 00000000..86b8557c--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/index.test.ts@@ -0,0 +1,85 @@+import type { UiContext } from './types/index.js'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { apply as hostApply } from '../index.js'+import { MachinesSection } from './components/machines-section.tsx'+import { apply, inject } from './index.js'+import { en, zh } from './locales/index.js'+import { MachinesStore } from './store/index.js'++function scriptedCtx(): {+ ctx: UiContext+ locale: { register: ReturnType<typeof vi.fn>, bind: ReturnType<typeof vi.fn> }+ slots: { inject: ReturnType<typeof vi.fn>, register: ReturnType<typeof vi.fn> }+ effects: Array<() => void>+} {+ const locale = {+ register: vi.fn(),+ bind: vi.fn(() => (key: string) => `t:${key}`),+ }+ const slots = {+ inject: vi.fn(),+ register: vi.fn(() => 'registration'),+ }+ const effects: Array<() => void> = []+ const ctx = {+ effect: vi.fn((callback: () => void) => { effects.push(callback) }),+ get: vi.fn(() => undefined),+ locale,+ slots,+ } as unknown as UiContext+ return { ctx, locale, slots, effects }+}++describe('ui-ssh client plugin', () => {+ it('host half apply is a no-op', () => {+ expect(hostApply()).toBeUndefined()+ })++ it('declares its inject topology', () => {+ expect(inject).toEqual(['slots', 'locale'])+ })++ it('registers the ssh dictionaries on activation', () => {+ const { ctx, locale, effects } = scriptedCtx()+ apply(ctx)+ expect(effects).toHaveLength(1)+ effects[0]?.()+ expect(locale.register).toHaveBeenCalledWith('ssh', { zh, en })+ expect(locale.bind).toHaveBeenCalledWith('ssh')+ })++ it('registers the settings section with a store-backed inject face', async () => {+ const { ctx, slots } = scriptedCtx()+ apply(ctx)+ expect(slots.inject).toHaveBeenCalledWith('settings.section', expect.any(Function))+ const contribution = slots.inject.mock.calls[0]?.[1] as () => unknown+ contribution()+ const options = slots.register.mock.calls[0]?.[0] as {+ name: string+ id: string+ order: number+ label: () => string+ locale: string+ inject: () => Record<string, unknown>+ }+ expect(options.name).toBe('settings.section')+ expect(options.id).toBe('dsh-tauri-ssh')+ expect(options.order).toBe(50)+ expect(options.label()).toBe('t:nav')+ expect(options.locale).toBe('ssh')+ const injected = options.inject()+ expect(injected.store).toBeInstanceOf(MachinesStore)+ expect(slots.register.mock.calls[0]?.[1]).toBe(MachinesSection)+ // Drive one store load so the window.fetch thunk the plugin installed+ // actually executes (stubbed: no network in tests).+ const fetchMock = vi.fn(async () => ({ json: async () => ({ ok: true, value: { items: [] } }) }) as unknown as Response)+ vi.stubGlobal('fetch', fetchMock)+ const store = injected.store as MachinesStore+ await store.load()+ expect(fetchMock).toHaveBeenCalledWith('/api-ssh', expect.objectContaining({ method: 'POST' }))+ })+})++afterEach(() => {+ vi.unstubAllGlobals()+})diff --git a/packages/dsh-tauri-ssh-ui/src/client/index.ts b/packages/dsh-tauri-ssh-ui/src/client/index.tsnew file mode 100644index 00000000..43b8199e--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/index.ts@@ -0,0 +1,39 @@+/**+ * SSH-machines settings page, browser half. Registers the `ssh` dictionary+ * and one `settings.section` entry; the page state lives in the injected+ * MachinesStore (machine CRUD and the connection plane, all through the host+ * plugin's /api-ssh route). Export discipline: thin apply, everything else+ * in feature modules.+ * @module dsh-tauri-ssh-ui/client+ */++import type { UiContext } from './types/index.js'+import { MachinesSection } from './components/machines-section.js'+import { SETTINGS_SECTION_ID, SETTINGS_SECTION_ORDER, SETTINGS_SECTION_SLOT, SSH_LOCALE_NS } from './constants/index.js'+import { en, zh } from './locales/index.js'+import { MachinesStore } from './store/index.js'++/** Required services: the settings slot seam and the locale seat. */+export const inject = ['slots', 'locale']++/**+ * Register the `ssh` dictionaries and the settings section, each once its+ * slot declaration is on the ledger.+ * @param ctx - client root context.+ */+export function apply(ctx: UiContext): void {+ ctx.effect(() => ctx.locale.register(SSH_LOCALE_NS, { zh, en }), 'dsh-tauri-ssh-ui: dictionaries')+ const t = ctx.locale.bind(SSH_LOCALE_NS)+ const store = new MachinesStore((url, init) => fetch(url, init))+ ctx.slots.inject(SETTINGS_SECTION_SLOT, () => ctx.slots.register({+ name: SETTINGS_SECTION_SLOT,+ id: SETTINGS_SECTION_ID,+ order: SETTINGS_SECTION_ORDER,+ label: () => t('nav'),+ locale: SSH_LOCALE_NS,+ inject: () => ({ store }),+ }, MachinesSection))+}++/** The dictionary key union, re-exported for the section props. */+export type { SshKey } from './locales/index.js'diff --git a/packages/dsh-tauri-ssh-ui/src/client/locales/index.test.ts b/packages/dsh-tauri-ssh-ui/src/client/locales/index.test.tsnew file mode 100644index 00000000..fb750546--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/locales/index.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest'+import { en, zh } from './index.js'++describe('locales', () => {+ it('en covers every zh key with no extras', () => {+ expect(Object.keys(en).sort()).toEqual(Object.keys(zh).sort())+ })++ it('ships non-empty string values only', () => {+ for (const [key, value] of Object.entries(zh)) {+ expect(value, `zh.${key}`).toBeTruthy()+ }+ for (const [key, value] of Object.entries(en)) {+ expect(value, `en.${key}`).toBeTruthy()+ }+ })+})diff --git a/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts b/packages/dsh-tauri-ssh-ui/src/client/locales/index.tsnew file mode 100644index 00000000..8047bc5c--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts@@ -0,0 +1,108 @@+/** The SSH-machines settings page dictionary (zh is the key-set source of truth). */++/** Simplified Chinese dictionary. */+export const zh = {+ 'nav': 'SSH 机器',+ 'title': 'SSH 远程机器',+ 'intro': '连接直接使用本机 ~/.ssh 的配置与密钥:支持 config 别名、IdentityFile 与默认密钥;密码和私钥口令可选,仅在密钥不可用时作为回退。',+ 'loading': '加载中…',+ 'empty': '还没有 SSH 机器。点击「添加机器」创建第一台。',+ 'configHosts': '来自 ~/.ssh/config 的主机',+ 'configHostsHint': '只读列表:连接时实时解析别名的 HostName/User/Port/IdentityFile。添加同 ID 的手动机器可覆盖别名,或用于设置密码与远端端口。',+ 'configTag': '~/.ssh/config',+ 'addMachine': '添加机器',+ 'refresh': '刷新',+ 'save': '保存',+ 'saveHint': '请填写机器 ID、名称和主机后再保存。',+ 'remove': '删除',+ 'test': '测试',+ 'connect': '连接',+ 'open': '打开',+ 'disconnect': '断开',+ 'secret.set': '已设置',+ 'secret.unset': '未设置',+ 'error.banner': '错误:',+ 'notice.testOk': '连接正常:',+ 'notice.disconnected': '已断开。',+ 'notice.connected': '已连接:',+ 'field.id': 'ID',+ 'field.name': '名称',+ 'field.host': '主机(或 config 别名)',+ 'field.port': '端口',+ 'field.user': '用户(可选)',+ 'field.remotePort': '远端端口',+ 'field.startCommand': '启动命令(可选)',+ 'field.password': '密码(可选)',+ 'field.passphrase': '私钥口令(可选)',+ 'field.color': '标识颜色',+ 'color.none': '默认',+ 'field.tintBorder': '同时着色边框',+ 'open.tip': '在新窗口中打开远端实例',+ 'status.disconnected': '未连接',+ 'status.connecting': '连接中…',+ 'status.connected': '已连接',+ 'progress.handshake': '正在建立 SSH 连接…',+ 'progress.starting': '正在启动远端实例…',+ 'progress.probing': '健康检查 {attempt}/{total}…',+ 'progress.installing': '正在安装 dsh(克隆 + 依赖 + 构建,约 5–15 分钟)…',+ 'install.action': '一键安装 dsh',+ 'install.hint': '远端未检测到 dsh。将执行官方安装脚本(克隆 deepseek-harness 仓库 + pnpm install + 构建 Web UI);如需使用自己的 git 仓库,请在插件配置中设置 installRepo。安装完成后自动连接。',+ 'install.done.copied': '安装完成,已复制本机 API Key,正在自动连接…',+ 'install.done.nokey': '安装完成。本机未找到 DEEPSEEK_API_KEY,请在远端 dsh Web 的 Models 页面配置后使用。',+ 'install.done.error': '安装完成,但凭据复制失败:',+} satisfies Record<string, string>++/** The dictionary key union. */+export type SshKey = keyof typeof zh++/** English dictionary, checked complete against the zh key set. */+export const en = {+ 'nav': 'SSH Machines',+ 'title': 'SSH Remote Machines',+ 'intro': 'Connections use this machine\'s ~/.ssh directly: config aliases, IdentityFile, and the default keys are honored; password and passphrase are optional fallbacks.',+ 'loading': 'Loading…',+ 'empty': 'No SSH machines yet. Click "Add machine" to create the first one.',+ 'configHosts': 'Hosts from ~/.ssh/config',+ 'configHostsHint': 'Read-only: each alias resolves HostName/User/Port/IdentityFile at connect time. Add a manual machine with the same ID to override it, or for password and remote-port needs.',+ 'configTag': '~/.ssh/config',+ 'addMachine': 'Add machine',+ 'refresh': 'Refresh',+ 'save': 'Save',+ 'saveHint': 'Fill in the machine ID, name, and host before saving.',+ 'remove': 'Remove',+ 'test': 'Test',+ 'connect': 'Connect',+ 'open': 'Open',+ 'disconnect': 'Disconnect',+ 'secret.set': 'set',+ 'secret.unset': 'not set',+ 'error.banner': 'Error: ',+ 'notice.testOk': 'Probe ok: ',+ 'notice.disconnected': 'Disconnected.',+ 'notice.connected': 'Connected: ',+ 'field.id': 'ID',+ 'field.name': 'Name',+ 'field.host': 'Host or config alias',+ 'field.port': 'Port',+ 'field.user': 'User (optional)',+ 'field.remotePort': 'Remote port',+ 'field.startCommand': 'Start command (optional)',+ 'field.password': 'Password (optional)',+ 'field.passphrase': 'Key passphrase (optional)',+ 'field.color': 'Color',+ 'color.none': 'Default',+ 'field.tintBorder': 'Also tint the border',+ 'open.tip': 'Open the remote instance in a new window',+ 'status.disconnected': 'Disconnected',+ 'status.connecting': 'Connecting…',+ 'status.connected': 'Connected',+ 'progress.handshake': 'Connecting over SSH…',+ 'progress.starting': 'Starting the remote instance…',+ 'progress.probing': 'Health check {attempt}/{total}…',+ 'progress.installing': 'Installing dsh (clone + deps + build, ~5–15 min)…',+ 'install.action': 'Install dsh',+ 'install.hint': 'No dsh found on the remote. This runs the official installer (clones deepseek-harness, pnpm install, builds the Web UI); set installRepo in the plugin config to use your own git repository. Auto-connects when done.',+ 'install.done.copied': 'Installed. Your API key was copied to the remote; auto-connecting…',+ 'install.done.nokey': 'Installed. No DEEPSEEK_API_KEY found locally; configure one on the remote Models page to use it.',+ 'install.done.error': 'Installed, but copying credentials failed: ',+} satisfies Record<SshKey, string>diff --git a/packages/dsh-tauri-ssh-ui/src/client/store/index.test.ts b/packages/dsh-tauri-ssh-ui/src/client/store/index.test.tsnew file mode 100644index 00000000..b69314a3--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/store/index.test.ts@@ -0,0 +1,363 @@+import type { FetchFn, MachineRow, SshApiResponse } from './index.js'+import { describe, expect, it, vi } from 'vitest'+import { machineRowOf, MachinesStore, savePayloadOf } from './index.js'++type FetchMock = ReturnType<typeof vi.fn<FetchFn>>++function fakeFetch(envelope: SshApiResponse): FetchMock {+ return vi.fn<FetchFn>(async () => ({ json: async () => envelope }) as unknown as Response)+}++function boot(envelope: SshApiResponse = { ok: true, value: { items: [] } }) {+ const fetchFn = fakeFetch(envelope)+ const store = new MachinesStore(fetchFn)+ return { store, fetchFn }+}++const machineA: MachineRow = {+ id: 'a',+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ hasPassword: true,+ hasPassphrase: false,+ remotePort: 3080,+}+const machineB: MachineRow = {+ ...machineA,+ id: 'b',+ name: 'beta',+ host: '10.0.0.2',+ port: 2222,+ user: 'deploy',+ hasPassword: false,+ hasPassphrase: true,+ remotePort: 3000,+ startCommand: 'dsh web --host 127.0.0.1 --port 3000',+}++describe('machineRowOf', () => {+ it('parses a well-formed redacted row', () => {+ expect(machineRowOf(machineA)).toEqual(machineA)+ expect(machineRowOf(machineB)).toEqual(machineB)+ })++ it('rejects malformed rows', () => {+ expect(machineRowOf(undefined)).toBeUndefined()+ expect(machineRowOf('x')).toBeUndefined()+ expect(machineRowOf({ ...machineA, id: '' })).toBeUndefined()+ expect(machineRowOf({ ...machineA, id: 5 })).toBeUndefined()+ expect(machineRowOf({ ...machineA, name: 5 })).toBeUndefined()+ expect(machineRowOf({ ...machineA, host: '' })).toBeUndefined()+ expect(machineRowOf({ ...machineA, user: 5 })).toBeUndefined()+ })++ it('falls back to defaults for absent numeric fields and optional startCommand', () => {+ const row = machineRowOf({ ...machineA, port: undefined, remotePort: undefined, startCommand: '', hasPassword: undefined })+ expect(row).toMatchObject({ port: 22, remotePort: 3080, hasPassword: false })+ expect(row).not.toHaveProperty('startCommand')+ })++ it('accepts an empty user (resolved from ~/.ssh config or the OS user)', () => {+ const row = machineRowOf({ ...machineA, user: '' })+ expect(row).toMatchObject({ user: '' })+ })+})++describe('savePayloadOf', () => {+ it('builds the config row and carries only typed secrets', () => {+ expect(savePayloadOf(machineB, { passphrase: 'PHRASE', password: '' })).toEqual({+ machineId: 'b',+ row: {+ name: 'beta',+ host: '10.0.0.2',+ port: 2222,+ user: 'deploy',+ remotePort: 3000,+ startCommand: 'dsh web --host 127.0.0.1 --port 3000',+ },+ secrets: { passphrase: 'PHRASE' },+ })+ expect(savePayloadOf(machineA, {})).toEqual({+ machineId: 'a',+ row: { name: 'alpha', host: '10.0.0.1', port: 22, user: 'root', remotePort: 3080 },+ })+ expect(savePayloadOf({ ...machineA, startCommand: '' }, {})).not.toHaveProperty('row.startCommand')+ })+})++describe('machinesStore', () => {+ it('loads machines, secret flags, and live statuses from machine.list', async () => {+ const { store } = boot({+ ok: true,+ value: {+ items: [+ { ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' },+ { ...machineB, state: 'disconnected', lastError: 'auth failed' },+ { ...machineA, id: 'c', name: 'gamma', state: 'disconnected' },+ ],+ },+ })+ await store.load()+ const state = store.getSnapshot()+ expect(state.status).toBe('ready')+ expect(state.machines.map(row => row.id)).toEqual(['a', 'b', 'c'])+ expect(state.machines[0]).toMatchObject({ hasPassword: true, hasPassphrase: false })+ expect(state.statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' })+ expect(state.statuses.b).toEqual({ state: 'disconnected', lastError: 'auth failed' })+ expect(state.statuses.c).toEqual({ state: 'disconnected' })+ })++ it('carries the live progress of in-flight operations', async () => {+ const { store } = boot({+ ok: true,+ value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } }] },+ })+ await store.load()+ expect(store.getSnapshot().statuses.a)+ .toEqual({ state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } })+ })++ it('polls without flipping the loading banner', async () => {+ const { store, fetchFn } = boot({+ ok: true,+ value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'handshake' } }] },+ })+ await store.load()+ fetchFn.mockClear()+ fetchFn.mockResolvedValueOnce({+ json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] } }),+ } as unknown as Response)+ await store.poll()+ const state = store.getSnapshot()+ expect(state.status).toBe('ready')+ expect(state.statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' })+ })++ it('tolerates a list response without the items key', async () => {+ const { store } = boot({ ok: true, value: {} })+ await store.load()+ expect(store.getSnapshot()).toMatchObject({ status: 'ready', machines: [], discovered: [], statuses: {} })+ })++ it('loads the discovered config aliases alongside the manual machines', async () => {+ const { store } = boot({+ ok: true,+ value: {+ items: [{ ...machineA, state: 'disconnected' }],+ discovered: [+ { ...machineA, id: 'dev', name: 'dev', host: 'dev', user: 'root', hasPassword: false, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:9' },+ { ...machineA, id: 'ci', name: 'ci', host: 'ci', user: '', hasPassword: false, state: 'disconnected' },+ ],+ },+ })+ await store.load()+ const state = store.getSnapshot()+ expect(state.machines.map(row => row.id)).toEqual(['a'])+ expect(state.discovered.map(row => row.id)).toEqual(['dev', 'ci'])+ expect(state.discovered[0]).toMatchObject({ host: 'dev', user: 'root', hasPassword: false, hasPassphrase: false })+ expect(state.statuses.dev).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:9' })+ expect(state.statuses.ci).toEqual({ state: 'disconnected' })+ })++ it('reports a list failure as a page error', async () => {+ const { store } = boot({ ok: false, error: { code: 'forbidden', message: 'loopback only' } })+ await store.load()+ expect(store.getSnapshot()).toMatchObject({ status: 'error', error: 'loopback only' })+ })++ it('reports poll failures without flipping the ready status', async () => {+ const { store, fetchFn } = boot()+ await store.load()+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: false, error: { code: 'forbidden', message: 'nope' } }) } as unknown as Response)+ await store.poll()+ expect(store.getSnapshot()).toMatchObject({ status: 'ready', error: 'nope' })+ })++ it('persists saves and removals through /api-ssh', async () => {+ const { store, fetchFn } = boot({+ ok: true,+ value: { items: [{ ...machineA, state: 'disconnected' }, { ...machineB, state: 'disconnected' }] },+ })+ await store.load()+ fetchFn.mockClear()+ await store.persist(+ [{ ...machineA, name: 'alpha-2' }],+ { a: { password: 'sekrit', passphrase: 'PHRASE' } },+ )+ const calls = fetchFn.mock.calls+ .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload: Record<string, unknown> })+ .filter(call => call.method !== 'machine.list')+ expect(calls).toHaveLength(2)+ expect(calls[0]).toMatchObject({+ method: 'machine.save',+ payload: {+ machineId: 'a',+ row: { name: 'alpha-2', host: '10.0.0.1', port: 22, user: 'root', remotePort: 3080 },+ secrets: { password: 'sekrit', passphrase: 'PHRASE' },+ },+ })+ expect(calls[1]).toEqual({ method: 'machine.remove', payload: { machineId: 'b' } })+ expect(store.getSnapshot().error).toBeNull()+ })++ it('persists only manual machines, never the discovered aliases', async () => {+ const { store, fetchFn } = boot({+ ok: true,+ value: {+ items: [{ ...machineA, state: 'disconnected' }],+ discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'disconnected' }],+ },+ })+ await store.load()+ fetchFn.mockClear()+ await store.persist([machineA], {})+ const calls = fetchFn.mock.calls+ .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload: Record<string, unknown> })+ .filter(call => call.method !== 'machine.list')+ expect(calls).toHaveLength(1)+ expect(calls[0]).toMatchObject({ method: 'machine.save', payload: { machineId: 'a' } })+ })++ it('reports persist failures without throwing', async () => {+ const { store, fetchFn } = boot({ ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } })+ await store.load()+ fetchFn.mockClear()+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: false, error: { code: 'settings-rejected', message: 'nope' } }) } as unknown as Response)+ await store.persist([machineA], {})+ expect(store.getSnapshot().error).toBe('nope')+ })++ it('tests a machine and publishes the banner', async () => {+ const { store, fetchFn } = boot()+ await store.load()+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: true, banner: 'Linux alpha' } }) } as unknown as Response)+ await store.test('a')+ const state = store.getSnapshot()+ expect(state.notice).toBe('Linux alpha')+ expect(state.busy).toEqual({})+ const [, init] = fetchFn.mock.calls[1] as [string, RequestInit]+ expect(JSON.parse(String(init.body))).toEqual({ method: 'machine.test', payload: { machineId: 'a' } })+ })++ it('falls back to defaults when a probe omits banner or message', async () => {+ const { store, fetchFn } = boot()+ await store.load()+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: true } }) } as unknown as Response)+ await store.test('a')+ expect(store.getSnapshot().notice).toBe('ok')+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: false } }) } as unknown as Response)+ await store.test('a')+ const state = store.getSnapshot()+ expect(state.notice).toBe('failed')+ expect(state.statuses.a).toEqual({ state: 'disconnected', lastError: 'failed' })+ })++ it('publishes failed probes with the failure message', async () => {+ const { store, fetchFn } = boot()+ await store.load()+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: false, message: 'auth failed' } }) } as unknown as Response)+ await store.test('a')+ const state = store.getSnapshot()+ expect(state.notice).toBe('auth failed')+ expect(state.statuses.a).toEqual({ state: 'disconnected', lastError: 'auth failed' })+ })++ it('connects, disconnects, and tracks busy state', async () => {+ const { store, fetchFn } = boot()+ await store.load()+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:49152' } }) } as unknown as Response)+ await store.connect('a')+ expect(store.getSnapshot().statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' })+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: {} }) } as unknown as Response)+ await store.disconnect('a')+ expect(store.getSnapshot().statuses.a).toEqual({ state: 'disconnected' })+ expect(store.getSnapshot().notice).toBe('disconnected')+ })++ it('marks a machine busy while a connection-plane op is in flight', async () => {+ const { store, fetchFn } = boot()+ await store.load()+ let release: (() => void) | undefined+ const gate = new Promise<void>((resolve) => {+ release = resolve+ })+ fetchFn.mockReturnValueOnce(gate.then(() => ({ json: async () => ({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:1' } }) }) as unknown as Response))+ const pending = store.connect('a')+ expect(store.getSnapshot().busy.a).toBe('connect')+ release!()+ await pending+ expect(store.getSnapshot().busy).toEqual({})+ })++ it('reports connection-plane failures as a banner error', async () => {+ const { store, fetchFn } = boot()+ await store.load()+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: false, error: { code: 'connect-failed', message: 'refused' } }) } as unknown as Response)+ await store.connect('a')+ expect(store.getSnapshot().error).toBe('refused')+ fetchFn.mockResolvedValueOnce({+ json: async () => {+ throw new Error('bad json')+ },+ } as unknown as Response)+ await store.test('a')+ expect(store.getSnapshot().error).toBe('bad json')+ fetchFn.mockResolvedValueOnce({++ json: async () => {+ // eslint-disable-next-line no-throw-literal -- deliberately non-Error: covers messageOf(String(error))+ throw 'boom'+ },+ } as unknown as Response)+ await store.test('a')+ expect(store.getSnapshot().error).toBe('boom')+ })++ it('carries the dshMissing marker on list rows', async () => {+ const { store } = boot({+ ok: true,+ value: { items: [{ ...machineA, state: 'disconnected', lastError: 'dsh is not installed', dshMissing: true }] },+ })+ await store.load()+ const status = store.getSnapshot().statuses.a+ expect(status?.dshMissing).toBe(true)+ expect(status?.lastError).toBe('dsh is not installed')+ })++ it('installs dsh, records the outcome, and refreshes', async () => {+ const { store, fetchFn } = boot()+ await store.load()+ fetchFn.mockResolvedValueOnce({+ json: async () => ({ ok: true, value: { dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true } }),+ } as unknown as Response)+ await store.install('a')+ const state = store.getSnapshot()+ expect(state.installResults.a).toEqual({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true })+ // The follow-up load refreshed the list (auto-connect status).+ expect(fetchFn.mock.calls.length).toBeGreaterThanOrEqual(2)+ expect(state.busy).toEqual({})+ })++ it('reports an install failure as a banner error', async () => {+ const { store, fetchFn } = boot()+ await store.load()+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: false, error: { code: 'machine-install-failed', message: 'pnpm: not found' } }) } as unknown as Response)+ await store.install('a')+ expect(store.getSnapshot().error).toBe('pnpm: not found')+ })++ it('exposes a uSES-compatible subscribe/getSnapshot seam', async () => {+ const { store } = boot()+ const listener = vi.fn()+ const unsubscribe = store.subscribe(listener)+ await store.load()+ expect(listener).toHaveBeenCalled()+ unsubscribe()+ const before = listener.mock.calls.length+ await store.load()+ expect(listener.mock.calls.length).toBe(before)+ expect(store.getSnapshot()).toBe(store.store.getSnapshot())+ })+})diff --git a/packages/dsh-tauri-ssh-ui/src/client/store/index.ts b/packages/dsh-tauri-ssh-ui/src/client/store/index.tsnew file mode 100644index 00000000..04263c76--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/store/index.ts@@ -0,0 +1,394 @@+/**+ * State owner of the SSH-machines settings page. Everything goes through the+ * host plugin's same-origin `/api-ssh` route: machine.list serves the config+ * rows (secrets replaced by presence flags), the live statuses, and the+ * connection plane; machine.save/machine.remove are the CRUD writes. The+ * upstream settings RPC is deliberately NOT used for this namespace — its+ * configuration-client allowlist is hard-coded upstream, and the plugin must+ * stay zero-upstream-change. Framework-agnostic: tests inject a fake fetch.+ * @module dsh-tauri-ssh-ui/client/store+ */++import { SSH_API_PATH } from '../constants/index.js'++/** One redacted machine row (secret fields live only in the form). */+export interface MachineRow {+ id: string+ name: string+ host: string+ port: number+ user: string+ hasPassword: boolean+ hasPassphrase: boolean+ remotePort: number+ startCommand?: string+ /** Optional identity color (any CSS color) shown as the machine's pip. */+ color?: string+ /** Whether the identity color also tints the machine card's border. */+ tintBorder?: boolean+}++/** Secret values the operator typed into the form (write-only direction). */+export interface SecretValues {+ password?: string+ passphrase?: string+}++/** Live transport status of one machine, from the /api-ssh list. */+export interface MachineStatus {+ state: 'disconnected' | 'connecting' | 'connected'+ tunnelBaseUrl?: string+ lastError?: string+ /** Whether the last failure was "dsh not installed on the remote" (offers install). */+ dshMissing?: boolean+ /** Live progress of the in-flight operation (phase codes translated by the UI). */+ progress?: { phase: 'handshake' | 'starting' | 'probing' | 'installing', attempt?: number, total?: number, log?: string }+}++/** Outcome of a machine.install call (the host's install result). */+export interface InstallResult {+ dshPath: string+ credentialsCopied: boolean+ credentialsError?: string+}++/** One machine row as the /api-ssh machine.list method returns it. */+export interface MachineListItem extends MachineRow, MachineStatus {}++/** The /api-ssh envelope (host plugin protocol). */+export type SshApiResponse+ = | { ok: true, value: unknown }+ | { ok: false, error: { code: string, message: string } }++/** Page state published to the component through the snapshot seam. */+export interface MachinesPageState {+ status: 'idle' | 'loading' | 'ready' | 'error'+ error: string | null+ /** Redacted machine rows in settings order (the stored, editable set). */+ machines: MachineRow[]+ /** Read-only rows discovered from the host's ~/.ssh/config (aliases). */+ discovered: MachineRow[]+ /** Live status per machine id. */+ statuses: Record<string, MachineStatus>+ /** One in-flight connection-plane op per machine id. */+ busy: Record<string, 'test' | 'connect' | 'disconnect' | 'install'>+ /** The latest connection-plane outcome, shown in the banner. */+ notice: string | null+ /** The latest install outcome per machine id (shown under the card). */+ installResults: Record<string, InstallResult>+}++/** The fetch seam (window.fetch in the browser, fakes in tests). */+export type FetchFn = (url: string, init: RequestInit) => Promise<Response>++/** uSES-compatible snapshot store (getSnapshot returns a fresh object per update). */+export interface SnapshotStore<T> {+ getSnapshot: () => T+ subscribe: (listener: () => void) => () => void+}++/** Create a snapshot store around one mutable state object. */+export function createSnapshotStore<T>(initial: T): SnapshotStore<T> & { update: (mutator: (state: T) => void) => void } {+ let state = initial+ const listeners = new Set<() => void>()+ return {+ getSnapshot: () => state,+ subscribe: (listener) => {+ listeners.add(listener)+ return () => listeners.delete(listener)+ },+ update: (mutator) => {+ const next = { ...state }+ mutator(next)+ state = next+ for (const listener of listeners) listener()+ },+ }+}++/** Operator-facing description of any failure. */+function messageOf(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++/** Parse one /api-ssh envelope; non-ok envelopes throw. */+async function envelopeOf(response: Response): Promise<SshApiResponse> {+ return await response.json() as SshApiResponse+}++/** Build a redacted machine row from one machine.list item. */+export function machineRowOf(value: unknown): MachineRow | undefined {+ if (typeof value !== 'object' || value === null)+ return undefined+ const row = value as Record<string, unknown>+ if (typeof row.id !== 'string' || row.id === '')+ return undefined+ if (typeof row.name !== 'string')+ return undefined+ if (typeof row.host !== 'string' || row.host === '')+ return undefined+ if (typeof row.user !== 'string')+ return undefined+ const port = typeof row.port === 'number' ? row.port : 22+ const remotePort = typeof row.remotePort === 'number' ? row.remotePort : 3080+ const startCommand = typeof row.startCommand === 'string' && row.startCommand !== ''+ ? row.startCommand+ : undefined+ const color = typeof row.color === 'string' && row.color !== '' ? row.color : undefined+ return {+ id: row.id,+ name: row.name,+ host: row.host,+ port,+ user: row.user,+ hasPassword: row.hasPassword === true,+ hasPassphrase: row.hasPassphrase === true,+ remotePort,+ ...startCommand === undefined ? {} : { startCommand },+ ...color === undefined ? {} : { color },+ ...row.tintBorder === true ? { tintBorder: true } : {},+ }+}++/** The machine.save config row shape (config fields only). */+export interface MachineSaveRow {+ name: string+ host: string+ port: number+ user: string+ remotePort: number+ startCommand?: string+ color?: string+ tintBorder?: boolean+}++/** Map one form row onto the machine.save payload (id + row + write-only secrets). */+export function savePayloadOf(machine: MachineRow, secrets: SecretValues): { machineId: string, row: MachineSaveRow, secrets?: SecretValues } {+ const row: MachineSaveRow = {+ name: machine.name,+ host: machine.host,+ port: machine.port,+ user: machine.user,+ remotePort: machine.remotePort,+ ...machine.startCommand === undefined || machine.startCommand === '' ? {} : { startCommand: machine.startCommand },+ ...machine.color === undefined || machine.color === '' ? {} : { color: machine.color },+ ...machine.tintBorder === true ? { tintBorder: true } : {},+ }+ const typed: SecretValues = {}+ if (secrets.password !== undefined && secrets.password !== '')+ typed.password = secrets.password+ if (secrets.passphrase !== undefined && secrets.passphrase !== '')+ typed.passphrase = secrets.passphrase+ const payload: { machineId: string, row: MachineSaveRow, secrets?: SecretValues } = { machineId: machine.id, row }+ if (Object.keys(typed).length > 0)+ payload.secrets = typed+ return payload+}++/**+ * The page store: machine CRUD and the connection plane, all through+ * /api-ssh. Every mutation settles the published state; failures surface as+ * `state.error`/`state.notice` rather than throws.+ */+export class MachinesStore {+ /** The published page state. */+ readonly store: SnapshotStore<MachinesPageState> & { update: (mutator: (state: MachinesPageState) => void) => void }++ /**+ * @param fetchFn - the /api-ssh transport (window.fetch in the browser).+ */+ constructor(private readonly fetchFn: FetchFn) {+ this.store = createSnapshotStore<MachinesPageState>({+ status: 'idle',+ error: null,+ machines: [],+ discovered: [],+ statuses: {},+ busy: {},+ notice: null,+ installResults: {},+ })+ }++ /** Snapshot subscribe seam for useSyncExternalStore. */+ subscribe = (listener: () => void): () => void => this.store.subscribe(listener)++ /** Snapshot read seam for useSyncExternalStore. */+ getSnapshot = (): MachinesPageState => this.store.getSnapshot()++ /** POST one connection-plane method and return its value; failures throw. */+ private async callApi<T>(method: string, payload: Record<string, unknown>): Promise<T> {+ const response = await this.fetchFn(SSH_API_PATH, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ method, payload }),+ })+ const envelope = await envelopeOf(response)+ if (!envelope.ok)+ throw new Error(envelope.error.message)+ return envelope.value as T+ }++ /** Apply one machine.list payload to the published state. */+ private applyList(list: { items?: MachineListItem[], discovered?: MachineListItem[] }): void {+ const machines = (list.items ?? []).map(machineRowOf).filter((row): row is MachineRow => row !== undefined)+ const discovered = (list.discovered ?? []).map(machineRowOf).filter((row): row is MachineRow => row !== undefined)+ const statuses: Record<string, MachineStatus> = {}+ for (const item of [...(list.items ?? []), ...(list.discovered ?? [])]) {+ const status: MachineStatus = { state: item.state }+ if (item.tunnelBaseUrl !== undefined)+ status.tunnelBaseUrl = item.tunnelBaseUrl+ if (item.lastError !== undefined)+ status.lastError = item.lastError+ if (item.dshMissing === true)+ status.dshMissing = true+ if (item.progress !== undefined)+ status.progress = item.progress+ statuses[item.id] = status+ }+ this.store.update((state) => {+ state.status = 'ready'+ state.error = null+ state.machines = machines+ state.discovered = discovered+ state.statuses = statuses+ })+ }++ /** Refresh machines, secret flags, and live statuses from machine.list. */+ async load(): Promise<void> {+ this.store.update((state) => {+ state.status = 'loading'+ state.error = null+ })+ try {+ this.applyList(await this.callApi<{ items?: MachineListItem[], discovered?: MachineListItem[] }>('machine.list', {}))+ }+ catch (error) {+ this.store.update((state) => {+ state.status = 'error'+ state.error = messageOf(error)+ })+ }+ }++ /** Silent refresh: same payload as load(), but never flips the loading banner. */+ async poll(): Promise<void> {+ try {+ this.applyList(await this.callApi<{ items?: MachineListItem[], discovered?: MachineListItem[] }>('machine.list', {}))+ }+ catch (error) {+ this.store.update((state) => {+ state.error = messageOf(error)+ })+ }+ }++ /**+ * Persist the form: machine.save per row (write-only secrets; absent fields+ * keep the stored value) and machine.remove for ids that vanished.+ * @param machines - the form's machine rows (id is the dict key).+ * @param secrets - secret values the operator typed, keyed by machine id.+ */+ async persist(machines: MachineRow[], secrets: Record<string, SecretValues>): Promise<void> {+ const previous = this.store.getSnapshot().machines+ const previousIds = new Set(previous.map(row => row.id))+ try {+ for (const machine of machines) {+ await this.callApi<Record<string, never>>('machine.save', savePayloadOf(machine, secrets[machine.id] ?? {}))+ }+ for (const id of previousIds) {+ if (!machines.some(row => row.id === id)) {+ await this.callApi<Record<string, never>>('machine.remove', { machineId: id })+ }+ }+ this.store.update((state) => {+ state.error = null+ })+ await this.load()+ }+ catch (error) {+ this.store.update((state) => {+ state.error = messageOf(error)+ })+ }+ }++ /** Mark one machine busy; failures settle the banner error. */+ private async withBusy(id: string, op: 'test' | 'connect' | 'disconnect' | 'install', action: () => Promise<void>): Promise<void> {+ this.store.update((state) => {+ state.busy[id] = op+ state.notice = null+ state.error = null+ })+ try {+ await action()+ }+ catch (error) {+ this.store.update((state) => {+ state.error = messageOf(error)+ })+ }+ finally {+ this.store.update((state) => {+ delete state.busy[id]+ })+ }+ }++ /** One-shot probe: runs `uname -srm` on the machine, never starts the instance. */+ async test(id: string): Promise<void> {+ await this.withBusy(id, 'test', async () => {+ const result = await this.callApi<{ ok: boolean, banner?: string, message?: string }>('machine.test', { machineId: id })+ if (result.ok) {+ this.store.update((state) => {+ state.notice = result.banner ?? 'ok'+ state.statuses[id] = { state: 'disconnected' }+ })+ }+ else {+ this.store.update((state) => {+ state.notice = result.message ?? 'failed'+ state.statuses[id] = { state: 'disconnected', lastError: result.message ?? 'failed' }+ })+ }+ })+ }++ /** Connect the machine: ensures the remote dsh instance and opens the tunnel. */+ async connect(id: string): Promise<void> {+ await this.withBusy(id, 'connect', async () => {+ const link = await this.callApi<{ tunnelBaseUrl: string }>('machine.connect', { machineId: id })+ this.store.update((state) => {+ state.statuses[id] = { state: 'connected', tunnelBaseUrl: link.tunnelBaseUrl }+ state.notice = link.tunnelBaseUrl+ })+ })+ }++ /** Tear down one machine's link. */+ async disconnect(id: string): Promise<void> {+ await this.withBusy(id, 'disconnect', async () => {+ await this.callApi<Record<string, never>>('machine.disconnect', { machineId: id })+ this.store.update((state) => {+ state.statuses[id] = { state: 'disconnected' }+ state.notice = 'disconnected'+ })+ })+ }++ /**+ * One-click remote dsh install: streams through the host's machine.install,+ * which auto-connects on success. A follow-up load picks up the auto-connect+ * status (the polling loop keeps refreshing while it is in flight).+ */+ async install(id: string): Promise<void> {+ await this.withBusy(id, 'install', async () => {+ const result = await this.callApi<InstallResult>('machine.install', { machineId: id })+ this.store.update((state) => {+ state.installResults[id] = result+ })+ await this.load()+ })+ }+}diff --git a/packages/dsh-tauri-ssh-ui/src/client/types/index.ts b/packages/dsh-tauri-ssh-ui/src/client/types/index.tsnew file mode 100644index 00000000..225cc53d--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/types/index.ts@@ -0,0 +1,40 @@+/**+ * Structural types of the DSH client services this plugin consumes. The+ * @deepseek-ai packages are private to the harness and never published; the+ * plugin declares local mirrors of the exact surfaces it touches (shapes+ * copied from the harness's own registrants) and never imports the private+ * packages at runtime — the loader calls `apply` with the real context and+ * duck-typing does the rest.+ * @module dsh-tauri-ssh-ui/client/types+ */++/** One settings-section registration option set. */+export interface SlotRegisterOptions {+ name: string+ id: string+ order: number+ label: () => string+ locale?: string+ inject?: () => Record<string, unknown>+}++/** The slots ledger face (a subset of the runtime SlotsService). */+export interface SlotsService {+ inject: (name: string, contribution: () => unknown) => void+ register: (options: SlotRegisterOptions, component: unknown) => unknown+}++/** The locale face (a subset of the locale service). */+export interface LocaleService {+ register: (ns: string, dictionaries: { zh: Record<string, string>, en: Record<string, string> }) => void+ bind: (ns: string) => (key: string) => string+}++/** The client root context this plugin's apply receives. */+export interface UiContext {+ effect: (execute: () => (() => void) | void, label?: string) => unknown+ get: <T = unknown>(name: string) => T+ on: (name: string, listener: (...args: unknown[]) => void) => () => boolean+ slots: SlotsService+ locale: LocaleService+}diff --git a/packages/dsh-tauri-ssh-ui/src/index.ts b/packages/dsh-tauri-ssh-ui/src/index.tsnew file mode 100644index 00000000..b79c7310--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/index.ts@@ -0,0 +1,10 @@+/**+ * The DSH remote-machine client plugin: the SSH-machines settings page. The+ * browser half lives in `./client` (locale dictionary + one+ * `settings.section` slot); this entry is the host-side loader stub — no+ * host-side behavior, the SSH kernel is the `dsh-tauri-ssh` host plugin.+ * @module dsh-tauri-ssh-ui+ */++/** Host plugin body — no host-side behavior; the SSH kernel is the ssh-remote host plugin. */+export function apply(): void {}diff --git a/packages/dsh-tauri-ssh-ui/tsconfig.json b/packages/dsh-tauri-ssh-ui/tsconfig.jsonnew file mode 100644index 00000000..789c0a3b--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/tsconfig.json@@ -0,0 +1,12 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "target": "es2024",+ "lib": ["ES2024", "DOM", "DOM.Iterable"],+ "types": ["node"],+ "exactOptionalPropertyTypes": true,+ "noImplicitOverride": true,+ "noUncheckedIndexedAccess": true+ },+ "include": ["src/**/*.ts", "src/**/*.tsx", "../../types/**/*.d.ts"]+}diff --git a/packages/dsh-tauri-ssh-ui/tsdown.config.ts b/packages/dsh-tauri-ssh-ui/tsdown.config.tsnew file mode 100644index 00000000..99cdeba5--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/tsdown.config.ts@@ -0,0 +1,5 @@+import { defineDshConfig } from 'dsh-tauri-tsdown'++// Host stub (src/index.ts) + browser client bundle (src/client/index.ts)+// wrapped in the dsh-client-modules closure factory.+export default defineDshConfig()diff --git a/packages/dsh-tauri-ssh/cordis.patch.yml b/packages/dsh-tauri-ssh/cordis.patch.ymlnew file mode 100644index 00000000..23b14aa5--- /dev/null+++ b/packages/dsh-tauri-ssh/cordis.patch.yml@@ -0,0 +1,3 @@+- insert:+ - id: ssh-remote+ name: dsh-tauri-sshdiff --git a/packages/dsh-tauri-ssh/package.json b/packages/dsh-tauri-ssh/package.jsonnew file mode 100644index 00000000..73b324ed--- /dev/null+++ b/packages/dsh-tauri-ssh/package.json@@ -0,0 +1,65 @@+{+ "name": "dsh-tauri-ssh",+ "type": "module",+ "version": "0.6.7",+ "description": "DSH remote-machine host plugin: SSH connection management, TOFU host keys, remote dsh web auto-start, loopback tunnels, and the same-origin /api-ssh route",+ "author": "Hairyf <[email protected]>",+ "license": "MIT",+ "homepage": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-ssh",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/dsh-tauri-desk/deepseek-harness-desktop.git"+ },+ "bugs": {+ "url": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/issues"+ },+ "keywords": [+ "dsh",+ "plugin",+ "dsh-plugin",+ "ssh",+ "remote",+ "tauri",+ "deepseek-harness"+ ],+ "sideEffects": false,+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ },+ "./package.json": "./package.json"+ },+ "main": "./dist/index.js",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "files": [+ "cordis.patch.yml",+ "dist"+ ],+ "dsh": {+ "bundle": {+ "patch": "./cordis.patch.yml"+ }+ },+ "scripts": {+ "build": "tsdown",+ "dev": "tsdown --watch",+ "prepublishOnly": "nr build",+ "test": "vitest run",+ "typecheck": "tsc"+ },+ "dependencies": {+ "pathe": "catalog:utils",+ "schemastery": "catalog:utils",+ "ssh2": "catalog:utils"+ },+ "devDependencies": {+ "@types/node": "catalog:types",+ "@types/ssh2": "catalog:types",+ "dsh-tauri-tsdown": "workspace:*",+ "tsdown": "catalog:cli",+ "typescript": "catalog:cli",+ "vitest": "catalog:testing"+ }+}diff --git a/packages/dsh-tauri-ssh/src/host/apply.test.ts b/packages/dsh-tauri-ssh/src/host/apply.test.tsnew file mode 100644index 00000000..5068bdce--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/apply.test.ts@@ -0,0 +1,420 @@+import type z from 'schemastery'+import type { Config as SshRemoteConfig } from './storage/index.js'+import type { SshHostContext } from './types/index.js'+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { homedir, tmpdir } from 'node:os'+import { join } from 'pathe'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { apply, inject, name, SshRemoteService } from './apply.js'+import { MACHINES_NAMESPACE } from './storage/index.js'+import { MachineId } from './types/index.js'++/** Scripted settings scope double. */+function scriptedSettings() {+ const doc: Record<string, unknown> = {}+ let lastNs = ''+ const watchers: Array<(next: unknown, prev: unknown) => void> = []+ const update = vi.fn(async (patch: Record<string, unknown>) => {+ doc[lastNs] = deepMerge((doc[lastNs] as Record<string, unknown> | undefined) ?? {}, patch)+ for (const watcher of watchers) watcher(doc, {})+ })+ const replace = vi.fn(async (section: Record<string, unknown>) => {+ doc[lastNs] = section+ for (const watcher of watchers) watcher(doc, {})+ })+ return {+ doc,+ update,+ replace,+ register: vi.fn((ns: string, _schema: z<unknown>, options?: { base?: unknown }) => {+ lastNs = ns+ const base = options?.base ?? {}+ const resolved = (): unknown => ({ ...(base as object), ...(doc[ns] as object | undefined) })+ return {+ get: () => resolved(),+ watch: (callback: (next: unknown, prev: unknown) => void) => {+ watchers.push(callback)+ return () => {}+ },+ update,+ replace,+ }+ }),+ set(ns: string, section: Record<string, unknown>): void {+ doc[ns] = section+ for (const watcher of watchers) watcher(doc, {})+ },+ }+}++/** Plain-object deep merge used by the scripted settings scope. */+function deepMerge(target: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> {+ const next: Record<string, unknown> = { ...target }+ for (const [key, value] of Object.entries(patch)) {+ if (typeof value === 'object' && value !== null && !Array.isArray(value)+ && typeof next[key] === 'object' && next[key] !== null && !Array.isArray(next[key])) {+ next[key] = deepMerge(next[key] as Record<string, unknown>, value as Record<string, unknown>)+ }+ else {+ next[key] = value+ }+ }+ return next+}++function scriptedHttpServer() {+ const routes: Array<{ kind: string, path: string, handler?: unknown }> = []+ return {+ routes,+ register: vi.fn((route: { kind: string, path: string, handler?: unknown }) => {+ routes.push(route)+ return () => {}+ }),+ }+}++/** Plugin config without the optional overrides; defaults are exercised separately. */+const baseConfig: SshRemoteConfig = {+ connectTimeoutMs: 15000,+ healthCheckTimeoutMs: 1000,+ healthPollIntervalMs: 5,+ healthPollAttempts: 3,+}++// Every service construction points the credential/discovery layer at a+// scratch ssh directory — the developer's real ~/.ssh is never read.+let sshDir: string++beforeEach(() => {+ sshDir = mkdtempSync(join(tmpdir(), 'ssh-index-'))+})++afterEach(() => {+ rmSync(sshDir, { recursive: true, force: true })+})++/** One scripted context: cordis-shaped surface without real cordis types. */+function scriptedCtx(settings: unknown, webServer: unknown): { ctx: SshHostContext, disposers: Array<() => void> } {+ const disposers: Array<() => void> = []+ const ctx = {+ provide: vi.fn(),+ effect: vi.fn((callback: () => (() => void) | void) => {+ const disposer = callback()+ if (typeof disposer === 'function')+ disposers.push(disposer)+ }),+ settings,+ webServer,+ } as unknown as SshHostContext+ return { ctx, disposers }+}++/** Construct the service on scripted settings/webServer doubles. */+function construct(config: SshRemoteConfig = baseConfig): { ctx: SshHostContext, service: SshRemoteService, disposers: Array<() => void> } {+ const { ctx, disposers } = scriptedCtx(scriptedSettings(), scriptedHttpServer())+ return { ctx, service: new SshRemoteService(ctx, { ...config, sshDir }), disposers }+}++function boot(overrides: {+ settings?: ReturnType<typeof scriptedSettings>+ webServer?: ReturnType<typeof scriptedHttpServer>+ config?: Partial<SshRemoteConfig>+} = {}) {+ const settings = overrides.settings ?? scriptedSettings()+ const webServer = overrides.webServer ?? scriptedHttpServer()+ const { ctx } = scriptedCtx(settings, webServer)+ const config = {+ ...baseConfig,+ knownHostsPath: join(homedir(), '.dsh', 'ssh', 'known-hosts.json'),+ sshDir,+ ...overrides.config,+ }+ const service = new SshRemoteService(ctx, config)+ return { ctx, settings, webServer, service }+}++function machine(id: string): Record<string, unknown> {+ return {+ id,+ name: `machine-${id}`,+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ password: 'sekrit',+ remotePort: 3080,+ }+}++describe('ssh-remote plugin', () => {+ it('declares its plugin metadata', () => {+ expect(name).toBe('dsh-tauri-ssh')+ expect(inject).toEqual(['settings', 'webServer'])+ expect(apply).toEqual(expect.any(Function))+ })++ it('ships the cordis plugin descriptor as the default export', async () => {+ const descriptor = (await import('./apply.js')).default+ expect(descriptor).toMatchObject({+ name: 'dsh-tauri-ssh',+ inject: ['settings', 'webServer'],+ Config: expect.anything(),+ })+ expect(descriptor.apply).toEqual(expect.any(Function))+ // The loader reads Config/inject from the default object: a bare function+ // default would lose both (config defaults never apply, services not injected).+ expect(descriptor.apply).toBe(apply)+ })++ it('registers the namespace and mounts the /api-ssh route', () => {+ const { settings, webServer } = boot()+ expect(settings.register).toHaveBeenCalledWith(String(MACHINES_NAMESPACE), expect.anything(), { base: { machines: {} } })+ expect(webServer.routes).toMatchObject([{ kind: 'prefix', path: '/api-ssh' }])+ expect(webServer.routes[0]?.handler).toEqual(expect.any(Function))+ })++ it('loads machine profiles from the settings namespace', () => {+ const settings = scriptedSettings()+ settings.set(String(MACHINES_NAMESPACE), { machines: { a: machine('a') } })+ const { service } = boot({ settings })+ const views = service.profileViews()+ expect(views.map(view => view.id)).toEqual(['a'])+ expect(views[0]).toMatchObject({ name: 'machine-a', hasPassword: true })+ expect(views[0]).not.toHaveProperty('password')+ })++ it('refreshes the manager when the namespace changes', () => {+ const settings = scriptedSettings()+ settings.set(String(MACHINES_NAMESPACE), { machines: { a: machine('a'), b: machine('b') } })+ const { service } = boot({ settings })+ expect(service.profileViews()).toHaveLength(2)+ settings.set(String(MACHINES_NAMESPACE), { machines: { a: machine('a') } })+ expect(service.profileViews().map(view => view.id)).toEqual(['a'])+ })++ it('rejects a dict key that disagrees with the profile id', () => {+ const settings = scriptedSettings()+ settings.set(String(MACHINES_NAMESPACE), { machines: { b: machine('a') } })+ expect(() => boot({ settings })).toThrow(/dict key must equal the profile id/)+ })++ it('exposes the manager connection plane', async () => {+ const { service } = boot()+ expect(service.status('ghost' as never)).toEqual({ machineId: 'ghost' as never, state: 'disconnected' })+ expect(service.profileViews()).toEqual([])+ await service.disconnect('a' as never)+ })++ it('forwards installs to the manager', async () => {+ const { service } = boot()+ const install = vi.spyOn(service.manager, 'install')+ .mockResolvedValue({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true })+ const result = await service.install(MachineId('a'))+ expect(install).toHaveBeenCalledWith(MachineId('a'), undefined)+ expect(result).toEqual({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true })+ })++ it('saves a machine through the settings scope and refreshes the manager', async () => {+ const { service, settings } = boot()+ await service.save('a' as never, {+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ remotePort: 3080,+ }, { password: 'sekrit', passphrase: 'PHRASE' })+ expect(settings.update).toHaveBeenCalledWith({+ machines: {+ a: {+ id: 'a',+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ remotePort: 3080,+ password: 'sekrit',+ passphrase: 'PHRASE',+ },+ },+ })+ const views = service.profileViews()+ expect(views.map(view => view.id)).toEqual(['a'])+ expect(views[0]).toMatchObject({ name: 'alpha', hasPassword: true })+ })++ it('keeps stored secrets on save unless rewritten', async () => {+ const settings = scriptedSettings()+ settings.set(String(MACHINES_NAMESPACE), { machines: { a: machine('a') } })+ const { service } = boot({ settings })+ await service.save('a' as never, {+ name: 'alpha-2',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ remotePort: 3080,+ })+ const views = service.profileViews()+ expect(views[0]).toMatchObject({ name: 'alpha-2', hasPassword: true })+ })++ it('keeps stored secrets on save and stores the start command', async () => {+ const settings = scriptedSettings()+ settings.set(String(MACHINES_NAMESPACE), {+ machines: { a: { ...machine('a'), passphrase: 'OLD-PHRASE' } },+ })+ const { service } = boot({ settings })+ await service.save('a' as never, {+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ remotePort: 3080,+ startCommand: 'dsh web --port 3080',+ }, { passphrase: 'NEW-PHRASE' })+ const views = service.profileViews()+ expect(views[0]).toMatchObject({+ name: 'alpha',+ hasPassword: true,+ hasPassphrase: true,+ startCommand: 'dsh web --port 3080',+ })+ })++ it('keeps whichever stored secrets exist and rewrites only typed ones', async () => {+ const settings = scriptedSettings()+ settings.set(String(MACHINES_NAMESPACE), {+ machines: { a: { ...machine('a'), password: undefined, passphrase: 'OLD-PHRASE' } },+ })+ const { service } = boot({ settings })+ await service.save('a' as never, {+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ remotePort: 3080,+ }, { password: 'NEW-PW' })+ const views = service.profileViews()+ expect(views[0]).toMatchObject({ name: 'alpha', hasPassword: true, hasPassphrase: true })+ const stored = settings.doc[String(MACHINES_NAMESPACE)] as { machines: Record<string, Record<string, unknown>> }+ expect(stored.machines.a?.password).toBe('NEW-PW')+ expect(stored.machines.a?.passphrase).toBe('OLD-PHRASE')+ })++ it('discovers ~/.ssh/config aliases as read-only machines', async () => {+ writeFileSync(join(sshDir, 'config'), [+ 'Host dev',+ ' HostName 10.0.0.9',+ ' User root',+ ' Port 2222',+ 'Host ci',+ ' IdentityFile ~/.ssh/special',+ 'Host *.example.com',+ 'Host !banned',+ ].join('\n'))+ const { service } = boot()+ const views = await service.discoveredViews()+ expect(views.map(view => view.id)).toEqual(['ci', 'dev'])+ expect(views[1]).toMatchObject({+ id: 'dev',+ name: 'dev',+ host: 'dev',+ port: 2222,+ user: 'root',+ hasPassword: false,+ hasPassphrase: false,+ remotePort: 3080,+ })+ expect(service.profileViews()).toEqual([])+ })++ it('lists no discovered machines without a config file', async () => {+ const { service } = boot()+ expect(await service.discoveredViews()).toEqual([])+ })++ it('lets a manual machine shadow a config alias', async () => {+ writeFileSync(join(sshDir, 'config'), 'Host dev\n User root\n')+ const settings = scriptedSettings()+ settings.set(String(MACHINES_NAMESPACE), { machines: { dev: { ...machine('dev'), host: '10.1.1.1' } } })+ const { service } = boot({ settings })+ expect((await service.discoveredViews()).map(view => view.id)).toEqual([])+ expect(service.profileViews().map(view => view.id)).toEqual(['dev'])+ })++ it('syncs discovered aliases into the manager profile map', async () => {+ writeFileSync(join(sshDir, 'config'), 'Host dev\n User root\n Port 2222\n')+ const { service } = boot()+ await service.disconnect(MachineId('dev'))+ const views = service.manager.profileViews()+ expect(views.map(view => view.id)).toEqual(['dev'])+ expect(views[0]).toMatchObject({ host: 'dev', port: 2222, user: 'root' })+ })++ it('applies the configured remote port and start command template to discovered aliases', async () => {+ writeFileSync(join(sshDir, 'config'), 'Host dev\n User root\n')+ const { service } = boot({ config: { remotePort: 3199, startCommand: '$HOME/.local/bin/dsh web --host 127.0.0.1 --port {port}' } })+ const views = await service.discoveredViews()+ expect(views[0]).toMatchObject({ id: 'dev', remotePort: 3199, startCommand: '$HOME/.local/bin/dsh web --host 127.0.0.1 --port 3199' })+ })++ it('applies the configured default start command to manual machines without their own', async () => {+ const settings = scriptedSettings()+ settings.set(String(MACHINES_NAMESPACE), { machines: { a: machine('a') } })+ const { service } = boot({ settings, config: { remotePort: 3080, startCommand: 'dsh web --port {port}' } })+ await service.disconnect('a' as never)+ const views = service.manager.profileViews()+ expect(views[0]).toMatchObject({ id: 'a', startCommand: 'dsh web --port 3080' })+ })++ it('keeps a manual start command over the configured default', async () => {+ const settings = scriptedSettings()+ settings.set(String(MACHINES_NAMESPACE), {+ machines: { a: { ...machine('a'), startCommand: 'custom dsh web' } },+ })+ const { service } = boot({ settings, config: { remotePort: 3080, startCommand: 'dsh web --port {port}' } })+ await service.disconnect('a' as never)+ const views = service.manager.profileViews()+ expect(views[0]).toMatchObject({ id: 'a', startCommand: 'custom dsh web' })+ })++ it('removes a machine through the settings scope', async () => {+ const settings = scriptedSettings()+ settings.set(String(MACHINES_NAMESPACE), { machines: { a: machine('a'), b: machine('b') } })+ const { service } = boot({ settings })+ await service.remove('a' as never)+ expect(service.profileViews().map(view => view.id)).toEqual(['b'])+ })++ it('delegates test and connect to the manager', async () => {+ const { service } = boot()+ await expect(service.test('ghost' as never)).rejects.toMatchObject({ code: 'machine-not-found' })+ await expect(service.connect('ghost' as never)).rejects.toMatchObject({ code: 'machine-not-found' })+ })++ it('defaults the known-hosts path from DSH_HOME or the home directory', () => {+ const previous = process.env.DSH_HOME+ try {+ process.env.DSH_HOME = '/tmp/dsh-home'+ expect(construct().service).toBeInstanceOf(SshRemoteService)+ delete process.env.DSH_HOME+ expect(construct().service).toBeInstanceOf(SshRemoteService)+ }+ finally {+ if (previous === undefined)+ delete process.env.DSH_HOME+ else process.env.DSH_HOME = previous+ }+ })++ it('disposes the manager when the context tears down', () => {+ const { service, disposers } = construct()+ const dispose = vi.spyOn(service.manager, 'dispose').mockResolvedValue(undefined)+ expect(disposers).toHaveLength(1)+ disposers[0]?.()+ expect(dispose).toHaveBeenCalledTimes(1)+ })++ it('apply constructs the service', () => {+ const { ctx } = construct()+ expect(apply(ctx, baseConfig)).toBeInstanceOf(SshRemoteService)+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/apply.ts b/packages/dsh-tauri-ssh/src/host/apply.tsnew file mode 100644index 00000000..20859c65--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/apply.ts@@ -0,0 +1,272 @@+/**+ * host/apply.ts — the DSH remote-machine host plugin assembly: registers the+ * `ssh-machines` settings namespace, owns the SSH connection manager (TOFU+ * host keys, remote `dsh web` auto-start, loopback tunnels), and mounts the+ * same-origin `/api-ssh` route on `ctx.webServer` for the settings page. No+ * upstream DSH source is touched: every integration is a documented cordis+ * extension point.+ * @module dsh-tauri-ssh/host/apply+ */++import type z from 'schemastery'+import type { SshApiHost } from './routes/index.js'+import type { SshHostBlock } from './service/ssh-config.js'+import type { MachinesValue, Config as SshRemoteConfig } from './storage/index.js'+import type { HostSettingsScope, MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, SshHostContext, SshInstallResult, SshLink, SshMachineStatus, SshTestResult } from './types/index.js'+import { homedir } from 'node:os'+import process from 'node:process'+import { join } from 'pathe'+import { SSH_API_PREFIX, SSH_PLUGIN_NAME } from '../shared/constants.js'+import { createSshApiHandler } from './routes/index.js'+import { KnownHostsStore } from './service/host-keys.js'+import { profileView, SshManager } from './service/manager.js'+import { discoverableHosts, loadSshConfigBlocks, lookupSshConfig, SshConfigResolver } from './service/ssh-config.js'+import { Ssh2Transport } from './service/transport.js'+import { ConfigSchema, DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT, MACHINES_NAMESPACE, machinesFromValue, MachinesSchema } from './storage/index.js'+import { MachineId } from './types/index.js'++/** Default location of the TOFU host-key document under the harness home. */+function defaultKnownHostsPath(): string {+ return join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), 'ssh', 'known-hosts.json')+}++/**+ * The plugin service: manager-backed connection plane plus the `/api-ssh`+ * handler face. Two machine sources feed the manager: the `ssh-machines`+ * settings namespace (manual machines, with secrets) and the host's own+ * `~/.ssh/config` (discovered Host aliases, read-only, no secrets) — a+ * manual machine with the same id as an alias shadows it.+ */+export class SshRemoteService implements SshApiHost {+ /** The connection manager (transport, TOFU store, and per-machine state). */+ readonly manager: SshManager++ /** The registered settings scope; the write path for machine CRUD. */+ private scope!: HostSettingsScope<MachinesValue>++ /** The ssh directory the discovered aliases and credentials come from. */+ private readonly sshDir: string++ /** The home directory used for `~` expansion while reading the ssh config. */+ private readonly homeDir: string++ /** The validated plugin config (defaults applied by schemastery). */+ private readonly config: SshRemoteConfig++ /**+ * @param ctx - the plugin context (settings + webServer available through inject).+ * @param config - the validated plugin config.+ */+ constructor(ctx: SshHostContext, config: SshRemoteConfig) {+ const knownHosts = new KnownHostsStore(config.knownHostsPath ?? defaultKnownHostsPath())+ this.homeDir = homedir()+ this.sshDir = config.sshDir ?? join(this.homeDir, '.ssh')+ this.config = config+ this.manager = new SshManager({+ transport: new Ssh2Transport(+ config.connectTimeoutMs,+ // Credentials come from the host's own ~/.ssh (config + identity+ // files), exactly like a local `ssh` invocation.+ new SshConfigResolver(this.sshDir, this.homeDir),+ ),+ knownHosts,+ config,+ // v8 ignore next -- deliberately empty status hook: the settings page polls /api-ssh+ emitStatus: () => {+ // The settings page polls status through /api-ssh; no live consumers.+ },+ })+ const scope = ctx.settings.register<MachinesValue>(String(MACHINES_NAMESPACE), MachinesSchema, {+ base: { machines: {} },+ })+ this.scope = scope+ this.manager.refreshProfiles(this.applyStartDefaults(this.manualProfiles()))+ scope.watch(() => {+ void this.syncProfiles()+ })+ // Mount the same-origin connection-plane API.+ ctx.webServer.register({+ kind: 'prefix',+ path: SSH_API_PREFIX,+ handler: createSshApiHandler(this),+ })+ ctx.effect(() => () => {+ void this.manager.dispose()+ })+ }++ /** The manual profiles, read fresh from the settings scope. */+ private manualProfiles(): Map<MachineId, MachineProfile> {+ return machinesFromValue(this.scope.get())+ }++ /** The configured default start command, `{port}` substituted, or none. */+ private defaultStartCommandFor(remotePort: number): string | undefined {+ const template = this.config.startCommand+ if (template === undefined || template === '')+ return undefined+ return template.replaceAll('{port}', String(remotePort))+ }++ /** Fill the configured default start command into profiles that lack one. */+ private applyStartDefaults(profiles: Map<MachineId, MachineProfile>): Map<MachineId, MachineProfile> {+ const next = new Map<MachineId, MachineProfile>()+ for (const [id, profile] of profiles) {+ const startCommand = profile.startCommand ?? this.defaultStartCommandFor(profile.remotePort)+ next.set(id, { ...profile, ...startCommand === undefined ? {} : { startCommand } })+ }+ return next+ }++ /** The discovered config-alias profiles, shadowed by manual ids. */+ private discoveredProfiles(+ blocks: SshHostBlock[],+ manual: Map<MachineId, MachineProfile>,+ ): Map<MachineId, MachineProfile> {+ const discovered = new Map<MachineId, MachineProfile>()+ const remotePort = this.config.remotePort ?? DEFAULT_REMOTE_PORT+ const startCommand = this.defaultStartCommandFor(remotePort)+ for (const alias of discoverableHosts(blocks)) {+ const id = MachineId(alias)+ if (manual.has(id))+ continue+ const settings = lookupSshConfig(blocks, alias)+ discovered.set(id, {+ id,+ name: alias,+ host: alias,+ port: settings.port ?? DEFAULT_SSH_PORT,+ user: settings.user ?? '',+ remotePort,+ ...startCommand === undefined ? {} : { startCommand },+ })+ }+ return discovered+ }++ /** Refresh the manager's profile map from both sources (settings + config). */+ private async syncProfiles(): Promise<void> {+ const manual = this.applyStartDefaults(this.manualProfiles())+ const blocks = await loadSshConfigBlocks(this.sshDir, this.homeDir)+ const merged = new Map<MachineId, MachineProfile>(manual)+ for (const [id, profile] of this.discoveredProfiles(blocks, manual)) merged.set(id, profile)+ this.manager.refreshProfiles(merged)+ }++ /** Redacted views of the manual machines only (the stored, editable set). */+ profileViews(): MachineView[] {+ return [...this.manualProfiles().values()].map(profileView)+ }++ /** Redacted views of the discovered `~/.ssh/config` aliases (read-only). */+ async discoveredViews(): Promise<MachineView[]> {+ const manual = this.manualProfiles()+ const blocks = await loadSshConfigBlocks(this.sshDir, this.homeDir)+ return [...this.discoveredProfiles(blocks, manual).values()].map(profileView)+ }++ status(machineId: MachineId): SshMachineStatus {+ return this.manager.status(machineId)+ }++ async test(machineId: MachineId, signal?: AbortSignal): Promise<SshTestResult> {+ await this.syncProfiles()+ return this.manager.test(machineId, signal)+ }++ async connect(machineId: MachineId, signal?: AbortSignal): Promise<SshLink> {+ await this.syncProfiles()+ return this.manager.connect(machineId, signal)+ }++ async disconnect(machineId: MachineId): Promise<void> {+ await this.syncProfiles()+ return this.manager.disconnect(machineId)+ }++ async install(machineId: MachineId, signal?: AbortSignal): Promise<SshInstallResult> {+ await this.syncProfiles()+ return this.manager.install(machineId, signal)+ }++ /**+ * Upsert one machine profile: merge the config row and any freshly typed+ * secrets into the stored profile (secrets omitted keep the stored value).+ * The scope write validates the whole section; the watch refreshes the+ * manager automatically.+ * @param machineId - the profile id (the settings dict key).+ * @param row - the config fields as the settings page edited them.+ * @param secrets - write-only secret values; absent fields keep stored ones.+ */+ async save(machineId: MachineId, row: MachineSaveRow, secrets?: MachineSecretWrite): Promise<void> {+ const machines = machinesFromValue(this.scope.get())+ const existing = machines.get(machineId)+ const next: MachineProfile = {+ id: machineId,+ name: row.name,+ host: row.host,+ port: row.port,+ user: row.user,+ remotePort: row.remotePort,+ }+ if (existing !== undefined) {+ if (existing.password !== undefined)+ next.password = existing.password+ if (existing.passphrase !== undefined)+ next.passphrase = existing.passphrase+ }+ if (row.startCommand !== undefined && row.startCommand !== '')+ next.startCommand = row.startCommand+ if (row.color !== undefined && row.color !== '')+ next.color = row.color+ if (row.tintBorder === true)+ next.tintBorder = true+ if (secrets !== undefined) {+ if (secrets.password !== undefined && secrets.password !== '')+ next.password = secrets.password+ if (secrets.passphrase !== undefined && secrets.passphrase !== '')+ next.passphrase = secrets.passphrase+ }+ await this.scope.update({ machines: { [machineId]: next } })+ }++ /**+ * Delete one machine profile. The owner scope's `replace` restates the full+ * section (in-process values include the stored secrets), so the removal is+ * exact and nothing else is touched.+ * @param machineId - the profile id to drop (idempotent for absent ids).+ */+ async remove(machineId: MachineId): Promise<void> {+ const machines = machinesFromValue(this.scope.get())+ machines.delete(machineId)+ await this.scope.replace({ machines: Object.fromEntries(machines) })+ }+}++/** Cordis plugin name. */+export const name = SSH_PLUGIN_NAME++/** Required services: the settings seam (namespace) and the webserver (route mount). */+export const inject = ['settings', 'webServer']++/** Validated plugin config; schemastery applies defaults before construction. */+export const Config: z<SshRemoteConfig> = ConfigSchema++/**+ * Cordis plugin entry: instantiate the service.+ * @param ctx - the plugin context.+ * @param config - the plugin config.+ * @returns the service instance.+ */+export function apply(ctx: SshHostContext, config: SshRemoteConfig): SshRemoteService {+ return new SshRemoteService(ctx, config)+}++/**+ * The cordis plugin descriptor. The loader imports the module and reads+ * `apply`/`Config`/`inject`/`name` from the **default export object** — a+ * bare function default carries neither the schema nor the inject list, so+ * config defaults would never apply and the settings/webServer services+ * would not be injected.+ */+export default { apply, Config, inject, name }diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.test.ts b/packages/dsh-tauri-ssh/src/host/routes/index.test.tsnew file mode 100644index 00000000..d4c9a075--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/routes/index.test.ts@@ -0,0 +1,389 @@+import type { MachineView, SshTestResult } from '../types/index.js'+import type { SshApiHost, SshApiResponse } from './index.js'+import { Buffer } from 'node:buffer'+import { IncomingMessage, ServerResponse } from 'node:http'+import { Socket } from 'node:net'+import { describe, expect, it, vi } from 'vitest'+import { MachineId, SshError } from '../types/index.js'+import { createSshApiHandler, isLoopbackPeer } from './index.js'++const view: MachineView = {+ id: MachineId('m1'),+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ hasPassword: true,+ hasPassphrase: false,+ remotePort: 3080,+}++function fakeHost(overrides: Partial<SshApiHost> = {}): SshApiHost {+ return {+ profileViews: () => [view],+ discoveredViews: async () => [],+ status: () => ({ machineId: MachineId('m1'), state: 'disconnected' }),+ test: async (): Promise<SshTestResult> => ({ ok: true, banner: 'Linux alpha' }),+ connect: async () => ({ tunnelBaseUrl: 'http://127.0.0.1:45678' }),+ disconnect: async () => {},+ install: async () => ({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true }),+ save: async () => {},+ remove: async () => {},+ ...overrides,+ }+}++/** Drive one request through the handler and collect the response. */+async function call(+ host: SshApiHost,+ body: string,+ options: { method?: string, address?: string } = {},+): Promise<{ status: number, body: SshApiResponse }> {+ const socket = new Socket()+ Object.defineProperty(socket, 'remoteAddress', { value: options.address ?? '127.0.0.1', configurable: true })+ const req = new IncomingMessage(socket)+ req.method = options.method ?? 'POST'+ const res = new ServerResponse(req)+ let status = 0+ let payload = ''+ res.writeHead = ((code: number) => {+ status = code+ return res+ }) as typeof res.writeHead+ res.end = ((chunk?: unknown) => {+ payload = String(chunk ?? '')+ return res+ }) as typeof res.end+ // Feed the body through the readable stream.+ req.push(Buffer.from(body))+ req.push(null)+ await createSshApiHandler(host)(req, res)+ return { status, body: JSON.parse(payload) as SshApiResponse }+}++describe('isLoopbackPeer', () => {+ it('accepts loopback addresses and rejects everything else', () => {+ expect(isLoopbackPeer('127.0.0.1')).toBe(true)+ expect(isLoopbackPeer('::1')).toBe(true)+ expect(isLoopbackPeer('::ffff:127.0.0.1')).toBe(true)+ expect(isLoopbackPeer('192.168.1.5')).toBe(false)+ expect(isLoopbackPeer(undefined)).toBe(false)+ })+})++describe('/api-ssh handler', () => {+ it('refuses non-loopback peers', async () => {+ const { status, body } = await call(fakeHost(), JSON.stringify({ method: 'machine.list' }), { address: '10.0.0.9' })+ expect(status).toBe(403)+ expect(body).toMatchObject({ ok: false, error: { code: 'forbidden' } })+ })++ it('refuses non-POST methods', async () => {+ const { status, body } = await call(fakeHost(), '', { method: 'GET' })+ expect(status).toBe(405)+ expect(body).toMatchObject({ ok: false, error: { code: 'method-not-allowed' } })+ })++ it('rejects malformed JSON and missing methods', async () => {+ const bad = await call(fakeHost(), 'not json')+ expect(bad.status).toBe(400)+ expect(bad.body).toMatchObject({ ok: false, error: { code: 'bad-request' } })+ const missing = await call(fakeHost(), JSON.stringify({ payload: {} }))+ expect(missing.status).toBe(400)+ expect(missing.body).toMatchObject({ ok: false, error: { code: 'bad-request' } })+ })++ it('lists machines with live status', async () => {+ const host = fakeHost({+ status: () => ({ machineId: MachineId('m1'), state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1', lastError: 'boom' }),+ })+ const { status, body } = await call(host, JSON.stringify({ method: 'machine.list' }))+ expect(status).toBe(200)+ expect(body).toEqual({+ ok: true,+ value: {+ items: [{+ ...view,+ state: 'connected',+ tunnelBaseUrl: 'http://127.0.0.1:1',+ lastError: 'boom',+ }],+ discovered: [],+ },+ })+ })++ it('lists discovered config aliases with their live status', async () => {+ const host = fakeHost({+ discoveredViews: async () => [{+ id: MachineId('dev'),+ name: 'dev',+ host: 'dev',+ port: 22,+ user: '',+ hasPassword: false,+ hasPassphrase: false,+ remotePort: 3080,+ }],+ status: (id: MachineId) => id === MachineId('dev')+ ? { machineId: id, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:2' }+ : { machineId: id, state: 'disconnected' },+ })+ const { status, body } = await call(host, JSON.stringify({ method: 'machine.list' }))+ expect(status).toBe(200)+ expect(body).toEqual({+ ok: true,+ value: {+ items: [{ ...view, state: 'disconnected' }],+ discovered: [{+ id: 'dev',+ name: 'dev',+ host: 'dev',+ port: 22,+ user: '',+ hasPassword: false,+ hasPassphrase: false,+ remotePort: 3080,+ state: 'connected',+ tunnelBaseUrl: 'http://127.0.0.1:2',+ }],+ },+ })+ })++ it('rides the live progress of an in-flight operation on list rows', async () => {+ const host = fakeHost({+ status: () => ({ machineId: MachineId('m1'), state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } }),+ })+ const { status, body } = await call(host, JSON.stringify({ method: 'machine.list' }))+ expect(status).toBe(200)+ expect(body).toEqual({+ ok: true,+ value: {+ items: [{+ ...view,+ state: 'connecting',+ progress: { phase: 'probing', attempt: 2, total: 30 },+ }],+ discovered: [],+ },+ })+ })++ it('lists machines without link fields while disconnected', async () => {+ const { status, body } = await call(fakeHost(), JSON.stringify({ method: 'machine.list' }))+ expect(status).toBe(200)+ expect(body).toEqual({ ok: true, value: { items: [{ ...view, state: 'disconnected' }], discovered: [] } })+ })++ it('rejects request bodies over the 64 KiB bound', async () => {+ const { status, body } = await call(fakeHost(), JSON.stringify({ method: 'machine.list', payload: { pad: 'x'.repeat(70 * 1024) } }))+ expect(status).toBe(400)+ expect(body).toMatchObject({ ok: false, error: { code: 'bad-request' } })+ })++ it('tests a machine', async () => {+ const host = fakeHost()+ const { status, body } = await call(host, JSON.stringify({ method: 'machine.test', payload: { machineId: 'm1' } }))+ expect(status).toBe(200)+ expect(body).toEqual({ ok: true, value: { ok: true, banner: 'Linux alpha' } })+ })++ it('connects a machine and returns the tunnel URL', async () => {+ const host = fakeHost()+ const { status, body } = await call(host, JSON.stringify({ method: 'machine.connect', payload: { machineId: 'm1' } }))+ expect(status).toBe(200)+ expect(body).toEqual({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:45678' } })+ })++ it('saves a machine with write-only secrets', async () => {+ const save = vi.fn(async () => {})+ const host = fakeHost({ save })+ const { status, body } = await call(host, JSON.stringify({+ method: 'machine.save',+ payload: {+ machineId: 'm1',+ row: {+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ remotePort: 3000,+ startCommand: 'dsh web --port 3000',+ },+ secrets: { password: 'PW', passphrase: 'PHRASE' },+ },+ }))+ expect(status).toBe(200)+ expect(body).toEqual({ ok: true, value: {} })+ expect(save).toHaveBeenCalledWith(+ MachineId('m1'),+ {+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ remotePort: 3000,+ startCommand: 'dsh web --port 3000',+ },+ { password: 'PW', passphrase: 'PHRASE' },+ )+ })++ it('rejects malformed machine.save payloads', async () => {+ const save = vi.fn(async () => {})+ const host = fakeHost({ save })+ const missingRow = await call(host, JSON.stringify({ method: 'machine.save', payload: { machineId: 'm1' } }))+ expect(missingRow.body).toEqual({ ok: false, error: { code: 'internal', message: 'missing row' } })+ const badName = await call(host, JSON.stringify({+ method: 'machine.save',+ payload: { machineId: 'm1', row: { name: '', host: 'x', user: 'u' } },+ }))+ expect(badName.body).toEqual({ ok: false, error: { code: 'internal', message: 'invalid row: name' } })+ const badUserType = await call(host, JSON.stringify({+ method: 'machine.save',+ payload: { machineId: 'm1', row: { name: 'a', host: 'x', user: 7 } },+ }))+ expect(badUserType.body).toEqual({ ok: false, error: { code: 'internal', message: 'invalid row: user' } })+ const badHost = await call(host, JSON.stringify({+ method: 'machine.save',+ payload: { machineId: 'm1', row: { name: 'a', host: '', user: 'u' } },+ }))+ expect(badHost.body).toEqual({ ok: false, error: { code: 'internal', message: 'invalid row: host' } })+ const badSecrets = await call(host, JSON.stringify({+ method: 'machine.save',+ payload: { machineId: 'm1', row: { name: 'a', host: 'x', user: 'u' }, secrets: 'nope' },+ }))+ expect(badSecrets.body).toEqual({ ok: false, error: { code: 'internal', message: 'invalid secrets' } })+ expect(save).not.toHaveBeenCalled()+ })++ it('applies row defaults for absent numeric fields', async () => {+ const save = vi.fn(async () => {})+ await call(fakeHost({ save }), JSON.stringify({+ method: 'machine.save',+ payload: { machineId: 'm1', row: { name: 'a', host: 'x', user: 'u', startCommand: '' } },+ }))+ expect(save).toHaveBeenCalledWith(+ MachineId('m1'),+ { name: 'a', host: 'x', port: 22, user: 'u', remotePort: 3080 },+ undefined,+ )+ })++ it('drops absent secret fields', async () => {+ const save = vi.fn(async () => {})+ await call(fakeHost({ save }), JSON.stringify({+ method: 'machine.save',+ payload: {+ machineId: 'm1',+ row: { name: 'a', host: 'x', user: 'u' },+ secrets: { passphrase: 'PHRASE' },+ },+ }))+ expect(save).toHaveBeenCalledWith(+ MachineId('m1'),+ { name: 'a', host: 'x', port: 22, user: 'u', remotePort: 3080 },+ { passphrase: 'PHRASE' },+ )+ await call(fakeHost({ save }), JSON.stringify({+ method: 'machine.save',+ payload: {+ machineId: 'm1',+ row: { name: 'a', host: 'x', user: 'u' },+ secrets: { password: 'P' },+ },+ }))+ expect(save).toHaveBeenLastCalledWith(+ MachineId('m1'),+ { name: 'a', host: 'x', port: 22, user: 'u', remotePort: 3080 },+ { password: 'P' },+ )+ })++ it('removes a machine', async () => {+ const remove = vi.fn(async () => {})+ const host = fakeHost({ remove })+ const { status, body } = await call(host, JSON.stringify({ method: 'machine.remove', payload: { machineId: 'm1' } }))+ expect(status).toBe(200)+ expect(body).toEqual({ ok: true, value: {} })+ expect(remove).toHaveBeenCalledWith(MachineId('m1'))+ })++ it('disconnects a machine', async () => {+ const host = fakeHost()+ const { status, body } = await call(host, JSON.stringify({ method: 'machine.disconnect', payload: { machineId: 'm1' } }))+ expect(status).toBe(200)+ expect(body).toEqual({ ok: true, value: {} })+ })++ it('installs dsh on a machine and returns the outcome', async () => {+ const install = vi.fn(async () => ({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true }))+ const host = fakeHost({ install })+ const { status, body } = await call(host, JSON.stringify({ method: 'machine.install', payload: { machineId: 'm1' } }))+ expect(status).toBe(200)+ expect(body).toEqual({+ ok: true,+ value: { dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true },+ })+ expect(install).toHaveBeenCalledWith(MachineId('m1'), expect.any(AbortSignal))+ })++ it('surfaces install failures on the envelope', async () => {+ const host = fakeHost({+ install: async () => { throw new SshError('machine-install-failed', MachineId('m1'), 'pnpm: not found') },+ })+ const { body } = await call(host, JSON.stringify({ method: 'machine.install', payload: { machineId: 'm1' } }))+ expect(body).toEqual({ ok: false, error: { code: 'machine-install-failed', message: 'pnpm: not found' } })+ })++ it('carries the dshMissing marker on list rows', async () => {+ const host = fakeHost({+ status: () => ({ machineId: MachineId('m1'), state: 'disconnected', dshMissing: true }),+ })+ const { body } = await call(host, JSON.stringify({ method: 'machine.list' }))+ expect(body).toMatchObject({ ok: true })+ const value = (body as { ok: true, value: { items: Array<Record<string, unknown>> } }).value+ expect(value.items[0]).toMatchObject({ dshMissing: true })+ })++ it('maps business failures onto the envelope', async () => {+ const host = fakeHost({+ test: async () => { throw new SshError('machine-connect-failed', MachineId('m1'), 'auth failed') },+ })+ const { status, body } = await call(host, JSON.stringify({ method: 'machine.test', payload: { machineId: 'm1' } }))+ expect(status).toBe(200)+ expect(body).toEqual({ ok: false, error: { code: 'machine-connect-failed', message: 'auth failed' } })+ })++ it('maps plain failures onto internal', async () => {+ const host = fakeHost({+ connect: async () => { throw new Error('tunnel broken') },+ })+ const { body } = await call(host, JSON.stringify({ method: 'machine.connect', payload: { machineId: 'm1' } }))+ expect(body).toEqual({ ok: false, error: { code: 'internal', message: 'tunnel broken' } })+ })++ it('maps non-Error failures onto internal', async () => {+ const host = fakeHost({++ test: async () => {+ // eslint-disable-next-line no-throw-literal -- deliberately non-Error: covers failureOf's String(error) arm+ throw 'boom'+ },+ })+ const { body } = await call(host, JSON.stringify({ method: 'machine.test', payload: { machineId: 'm1' } }))+ expect(body).toEqual({ ok: false, error: { code: 'internal', message: 'boom' } })+ })++ it('requires a machineId on actions', async () => {+ const { body } = await call(fakeHost(), JSON.stringify({ method: 'machine.test', payload: {} }))+ expect(body).toEqual({ ok: false, error: { code: 'internal', message: 'missing machineId' } })+ })++ it('rejects unknown methods', async () => {+ const { status, body } = await call(fakeHost(), JSON.stringify({ method: 'machine.warp' }))+ expect(status).toBe(404)+ expect(body).toMatchObject({ ok: false, error: { code: 'unknown-method' } })+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.ts b/packages/dsh-tauri-ssh/src/host/routes/index.tsnew file mode 100644index 00000000..d43387cf--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/routes/index.ts@@ -0,0 +1,245 @@+/**+ * The plugin's own HTTP API, mounted by the plugin on `ctx.webServer` under+ * `/api-ssh` (same-origin with the web UI; no upstream gateway changes).+ * Loopback-only by construction: non-loopback peers are refused before any+ * dispatch. The protocol is a minimal JSON envelope:+ *+ * POST /api-ssh { "method": "machine.list", "payload": {} }+ * → 200 { "ok": true, "value": ... } | { "ok": false, "error": { "code", "message" } }+ *+ * Machines are stored in the `ssh-machines` settings namespace; this API only+ * serves the connection plane (list/test/connect/disconnect) and the CRUD+ * writes (save/remove), which is exactly what the settings page cannot do+ * through the settings domain.+ * @module dsh-tauri-ssh/host/routes+ */++import type { IncomingMessage, ServerResponse } from 'node:http'+import type { MachineSaveRow, MachineSecretWrite, MachineView, SshInstallResult, SshMachineStatus, SshTestResult } from '../types/index.js'+import { Buffer } from 'node:buffer'+import { MachineId, SshError } from '../types/index.js'++/** One request envelope. */+export interface SshApiRequest {+ method: string+ payload?: unknown+}++/** One response envelope. */+export type SshApiResponse+ = | { ok: true, value: unknown }+ | { ok: false, error: { code: string, message: string } }++/**+ * The connection-plane method set (CRUD lives here too: the settings RPC only+ * serves an upstream allowlist, so the page writes through this route).+ */+export type SshApiMethod+ = | 'machine.list'+ | 'machine.test'+ | 'machine.connect'+ | 'machine.disconnect'+ | 'machine.install'+ | 'machine.save'+ | 'machine.remove'++/** A machine list row: the redacted profile plus its live status. */+export interface SshMachineListItem extends MachineView {+ state: SshMachineStatus['state']+ tunnelBaseUrl?: string+ lastError?: string+ dshMissing?: boolean+}++/** The manager face this API needs (the plugin's service). */+export interface SshApiHost {+ profileViews: () => MachineView[]+ /** The read-only `~/.ssh/config` alias machines (awaits the config read). */+ discoveredViews: () => Promise<MachineView[]>+ status: (machineId: MachineId) => SshMachineStatus+ test: (machineId: MachineId, signal?: AbortSignal) => Promise<SshTestResult>+ connect: (machineId: MachineId, signal?: AbortSignal) => Promise<{ tunnelBaseUrl: string }>+ disconnect: (machineId: MachineId) => Promise<void>+ /** One-shot remote dsh install; a successful install auto-connects. */+ install: (machineId: MachineId, signal?: AbortSignal) => Promise<SshInstallResult>+ save: (machineId: MachineId, row: MachineSaveRow, secrets?: MachineSecretWrite) => Promise<void>+ remove: (machineId: MachineId) => Promise<void>+}++/** Whether a socket peer is loopback (the only allowed caller of this API). */+export function isLoopbackPeer(address: string | undefined): boolean {+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'+}++/** Map one business failure onto the envelope. */+function failureOf(error: unknown): { code: string, message: string } {+ if (error instanceof SshError) {+ return { code: error.code, message: error.message }+ }+ return { code: 'internal', message: error instanceof Error ? error.message : String(error) }+}++/** Read and parse the request body (bounded). */+async function readBody(req: IncomingMessage): Promise<unknown> {+ const chunks: Buffer[] = []+ let size = 0+ for await (const chunk of req) {+ const buffer = chunk as Buffer+ size += buffer.length+ if (size > 64 * 1024)+ throw new Error('request body too large')+ chunks.push(buffer)+ }+ return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown+}++/**+ * Build the `/api-ssh` request handler over one service.+ * @param host - the manager-backed service face.+ * @returns the node:http handler (owns the full response lifecycle).+ */+export function createSshApiHandler(host: SshApiHost): (req: IncomingMessage, res: ServerResponse) => Promise<void> {+ return async (req, res) => {+ const respond = (status: number, body: SshApiResponse): void => {+ res.writeHead(status, { 'content-type': 'application/json' })+ res.end(JSON.stringify(body))+ }+ if (!isLoopbackPeer(req.socket.remoteAddress)) {+ respond(403, { ok: false, error: { code: 'forbidden', message: 'this API is loopback-only' } })+ return+ }+ if (req.method !== 'POST') {+ respond(405, { ok: false, error: { code: 'method-not-allowed', message: 'POST only' } })+ return+ }+ let request: SshApiRequest+ try {+ request = await readBody(req) as SshApiRequest+ }+ catch {+ respond(400, { ok: false, error: { code: 'bad-request', message: 'malformed JSON body' } })+ return+ }+ if (typeof request.method !== 'string' || request.method === '') {+ respond(400, { ok: false, error: { code: 'bad-request', message: 'missing method' } })+ return+ }+ const payload = (request.payload ?? {}) as Record<string, unknown>+ try {+ switch (request.method as SshApiMethod) {+ case 'machine.list': {+ const items: SshMachineListItem[] = host.profileViews().map(view => listItemOf(host, view))+ const discovered: SshMachineListItem[] = (await host.discoveredViews()).map(view => listItemOf(host, view))+ respond(200, { ok: true, value: { items, discovered } })+ return+ }+ case 'machine.test': {+ const value = await host.test(machineIdOf(payload), new AbortController().signal)+ respond(200, { ok: true, value })+ return+ }+ case 'machine.connect': {+ const link = await host.connect(machineIdOf(payload), new AbortController().signal)+ respond(200, { ok: true, value: { tunnelBaseUrl: link.tunnelBaseUrl } })+ return+ }+ case 'machine.disconnect': {+ await host.disconnect(machineIdOf(payload))+ respond(200, { ok: true, value: {} })+ return+ }+ case 'machine.install': {+ const value = await host.install(machineIdOf(payload), new AbortController().signal)+ respond(200, { ok: true, value })+ return+ }+ case 'machine.save': {+ const machineId = machineIdOf(payload)+ const row = saveRowOf(payload)+ const secrets = secretsOf(payload)+ await host.save(machineId, row, secrets)+ respond(200, { ok: true, value: {} })+ return+ }+ case 'machine.remove': {+ const machineId = machineIdOf(payload)+ await host.remove(machineId)+ respond(200, { ok: true, value: {} })+ return+ }+ default:+ respond(404, { ok: false, error: { code: 'unknown-method', message: `unknown method "${request.method}"` } })+ }+ }+ catch (error) {+ respond(200, { ok: false, error: failureOf(error) })+ }+ }+}++/** Read the machineId payload field; missing payloads fail loud. */+function machineIdOf(payload: Record<string, unknown>): MachineId {+ if (typeof payload.machineId !== 'string' || payload.machineId === '') {+ throw new Error('missing machineId')+ }+ return MachineId(payload.machineId)+}++/** One list row: the redacted view plus its live status. */+function listItemOf(host: SshApiHost, view: MachineView): SshMachineListItem {+ const status = host.status(view.id)+ return {+ ...view,+ state: status.state,+ ...status.tunnelBaseUrl === undefined ? {} : { tunnelBaseUrl: status.tunnelBaseUrl },+ ...status.lastError === undefined ? {} : { lastError: status.lastError },+ ...status.dshMissing === true ? { dshMissing: true } : {},+ ...status.progress === undefined ? {} : { progress: status.progress },+ }+}++/** Validate one machine.save config row; defaults mirror the schema. */+function saveRowOf(payload: Record<string, unknown>): MachineSaveRow {+ const row = payload.row+ if (typeof row !== 'object' || row === null)+ throw new Error('missing row')+ const value = row as Record<string, unknown>+ if (typeof value.name !== 'string' || value.name === '')+ throw new Error('invalid row: name')+ if (typeof value.host !== 'string' || value.host === '')+ throw new Error('invalid row: host')+ if (typeof value.user !== 'string')+ throw new Error('invalid row: user')+ const port = typeof value.port === 'number' ? value.port : 22+ const remotePort = typeof value.remotePort === 'number' ? value.remotePort : 3080+ const startCommand = typeof value.startCommand === 'string' && value.startCommand !== ''+ ? value.startCommand+ : undefined+ const color = typeof value.color === 'string' && value.color !== '' ? value.color : undefined+ return {+ name: value.name,+ host: value.host,+ port,+ user: value.user,+ remotePort,+ ...startCommand === undefined ? {} : { startCommand },+ ...color === undefined ? {} : { color },+ ...value.tintBorder === true ? { tintBorder: true } : {},+ }+}++/** Validate the write-only secret block; absent or empty fields are dropped. */+function secretsOf(payload: Record<string, unknown>): MachineSecretWrite | undefined {+ const secrets = payload.secrets+ if (secrets === undefined)+ return undefined+ if (typeof secrets !== 'object' || secrets === null)+ throw new Error('invalid secrets')+ const value = secrets as Record<string, unknown>+ const out: MachineSecretWrite = {}+ if (typeof value.password === 'string' && value.password !== '')+ out.password = value.password+ if (typeof value.passphrase === 'string' && value.passphrase !== '')+ out.passphrase = value.passphrase+ return out+}diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.tsnew file mode 100644index 00000000..95284974--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts@@ -0,0 +1,292 @@+import type { MachineProfile } from '../types/index.js'+import type { SshExecOptions, SshExecResult, SshSession } from './transport.js'+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'pathe'+import { afterEach, describe, expect, it } from 'vitest'+import { MachineId } from '../types/index.js'+import {+ credentialsCopyCommand,+ defaultStartCommand,+ describeExecFailure,+ DshMissingError,+ ensureRemoteInstance,+ firstLineOf,+ healthCheckCommand,+ installCommandFor,+ OFFICIAL_INSTALL_REPO,+ probeDshCommand,+ readEnvCredentials,+ startCommandFor,+} from './bootstrap.js'++const profile: MachineProfile = {+ id: MachineId('m1'),+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ remotePort: 3080,+}++/** The dsh-path answer a remote probe would print. */+const RESOLVED_DSH = '/usr/local/bin/dsh'++class FakeSession implements SshSession {+ commands: string[] = []++ constructor(private readonly responder: (command: string, index: number) => SshExecResult) {}++ exec(command: string, _options?: SshExecOptions): Promise<SshExecResult> {+ this.commands.push(command)+ return Promise.resolve(this.responder(command, this.commands.length - 1))+ }++ openTunnel(): Promise<never> {+ throw new Error('unused')+ }++ onClosed(): void {}++ close(): Promise<void> {+ return Promise.resolve()+ }+}++const tempDirs: string[] = []++function tempDir(): string {+ const dir = mkdtempSync(join(tmpdir(), 'dsh-remote-bootstrap-'))+ tempDirs.push(dir)+ return dir+}++afterEach(() => {+ for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true })+})++describe('remote instance commands', () => {+ it('builds the default start command from the profile port', () => {+ expect(defaultStartCommand(profile)).toBe('dsh web --host 127.0.0.1 --port 3080')+ })++ it('honors the profile startCommand override and ensures the log directory', () => {+ const overridden: MachineProfile = { ...profile, startCommand: 'dsh web --port 4000' }+ expect(startCommandFor(overridden))+ .toBe('mkdir -p "$HOME/.dsh" && ( dsh web --port 4000 >>"$HOME/.dsh/dsh-remote-web.log" 2>&1 < /dev/null & ) &')+ })++ it('builds the detached default start with log redirection', () => {+ expect(startCommandFor(profile))+ .toBe('mkdir -p "$HOME/.dsh" && ( dsh web --host 127.0.0.1 --port 3080 >>"$HOME/.dsh/dsh-remote-web.log" 2>&1 < /dev/null & ) &')+ })++ it('substitutes a resolved dsh path into the default start command', () => {+ expect(startCommandFor(profile, RESOLVED_DSH))+ .toBe('mkdir -p "$HOME/.dsh" && ( /usr/local/bin/dsh web --host 127.0.0.1 --port 3080 >>"$HOME/.dsh/dsh-remote-web.log" 2>&1 < /dev/null & ) &')+ })++ it('keeps the profile override untouched when a dsh path is known', () => {+ const overridden: MachineProfile = { ...profile, startCommand: 'my-launcher web' }+ expect(startCommandFor(overridden, RESOLVED_DSH)).toContain('my-launcher web')+ })++ it('builds a curl health probe with a bounded deadline', () => {+ expect(healthCheckCommand(3080, 2500)).toBe('curl -s -o /dev/null -m 3 -w \'%{http_code}\' http://127.0.0.1:3080/')+ expect(healthCheckCommand(4000, 100)).toBe('curl -s -o /dev/null -m 1 -w \'%{http_code}\' http://127.0.0.1:4000/')+ })++ it('summarizes a failed command for operators', () => {+ expect(describeExecFailure(1, 'bash: dsh: command not found\n')).toBe('exit 1: bash: dsh: command not found')+ expect(describeExecFailure(null, ' ')).toBe('exit ?')+ })+})++describe('dsh probe', () => {+ it('checks PATH, then the installer links, and never fails', () => {+ const command = probeDshCommand()+ expect(command).toContain('command -v dsh')+ expect(command).toContain('"$HOME/.local/bin/dsh"')+ expect(command).toContain('"$HOME/.dsh/source/current/bin/dsh"')+ expect(command).toContain('true')+ // Each fallback is a braced group: a successful earlier arm must+ // short-circuit the chain instead of firing the later && printf arms too.+ expect(command).toMatch(/\{ test -x "\$HOME\/\.local\/bin\/dsh" && printf/)+ })++ it('takes the first non-empty line of a probe result', () => {+ expect(firstLineOf('/usr/local/bin/dsh\n/other/bin/dsh\n')).toBe('/usr/local/bin/dsh')+ expect(firstLineOf('\n \n/usr/local/bin/dsh')).toBe('/usr/local/bin/dsh')+ expect(firstLineOf(' ')).toBe('')+ expect(firstLineOf('')).toBe('')+ })+})++describe('install commands', () => {+ it('builds the built-in install from the official repo default', () => {+ const command = installCommandFor({})+ expect(command).toContain(`git clone --depth 1 '${OFFICIAL_INSTALL_REPO}' "$HOME/.dsh/source/master"`)+ expect(command).toContain('corepack enable pnpm')+ expect(command).toContain('npm install -g pnpm')+ expect(command).toContain('pnpm install')+ expect(command).toContain('pnpm run build')+ expect(command).toContain('ln -sfn "$HOME/.dsh/source/current/bin/dsh" "$HOME/.local/bin/dsh"')+ expect(command).toContain('rm -rf "$HOME/.dsh/source/master" "$HOME/.dsh/source/current"')+ expect(command).toContain('set -e')+ })++ it('clones a configured repo with an optional ref', () => {+ const command = installCommandFor({ installRepo: 'https://git.example.com/team/dsh.git' })+ expect(command).toContain(`git clone --depth 1 'https://git.example.com/team/dsh.git' "$HOME/.dsh/source/master"`)+ const withRef = installCommandFor({+ installRepo: '[email protected]:me/dsh.git',+ installRef: 'snapshots/2026',+ })+ expect(withRef).toContain(`git clone --depth 1 --branch 'snapshots/2026' '[email protected]:me/dsh.git' "$HOME/.dsh/source/master"`)+ })+})++describe('credentials', () => {+ it('reads the DEEPSEEK keys from a dsh .env document', () => {+ const dir = tempDir()+ const env = join(dir, '.env')+ writeFileSync(env, 'OTHER=1\nDEEPSEEK_API_KEY=sk-test-123\nDEEPSEEK_BASE_URL=https://api.example.com\n')+ expect(readEnvCredentials(env)).toEqual({+ apiKey: 'sk-test-123',+ baseUrl: 'https://api.example.com',+ })+ })++ it('strips surrounding quotes and treats blank keys as absent', () => {+ const dir = tempDir()+ const env = join(dir, '.env')+ writeFileSync(env, 'DEEPSEEK_API_KEY="sk-quoted"\nDEEPSEEK_BASE_URL=\n')+ expect(readEnvCredentials(env)).toEqual({ apiKey: 'sk-quoted' })+ })++ it('reports no credentials for a missing document', () => {+ expect(readEnvCredentials(join(tempDir(), 'nope.env'))).toEqual({})+ })++ it('writes credentials into the remote .env without clobbering an existing key', () => {+ const command = credentialsCopyCommand({ apiKey: 'sk-\'quoted\'', baseUrl: 'https://api.example.com' })+ expect(command).toContain(`printf 'DEEPSEEK_API_KEY=%s\\n' 'sk-'\\''quoted'\\'''`)+ expect(command).toContain('DEEPSEEK_BASE_URL')+ expect(command).toContain('grep -q \'^DEEPSEEK_API_KEY=\'')+ expect(command).toContain('echo copied')+ expect(command).toContain('echo existing')+ expect(command).toContain('umask 077')+ })+})++describe('ensureRemoteInstance', () => {+ it('skips start when the instance already answers', async () => {+ const session = new FakeSession(() => ({ code: 0, stdout: '200', stderr: '' }))+ await expect(ensureRemoteInstance(session, profile, 1000, 10, 3)).resolves.toBe('10.0.0.1:3080')+ expect(session.commands).toHaveLength(1)+ expect(session.commands[0]).toContain('curl')+ })++ it('auto-starts when absent and reports the healthy address after polling', async () => {+ const session = new FakeSession((_command, index) => {+ // 1 = port probe (refused), 2 = dsh probe, 3 = start, 4 = post-start probe (healthy).+ if (index === 1)+ return { code: 0, stdout: RESOLVED_DSH, stderr: '' }+ if (index === 2)+ return { code: 0, stdout: '', stderr: '' }+ if (index === 3)+ return { code: 0, stdout: '200', stderr: '' }+ return { code: 7, stdout: '', stderr: 'refused' }+ })+ await expect(ensureRemoteInstance(session, profile, 1000, 5, 3)).resolves.toBe('10.0.0.1:3080')+ expect(session.commands[2]).toContain(`${RESOLVED_DSH} web --host 127.0.0.1 --port 3080`)+ })++ it('reports the bootstrap phases through the progress callback', async () => {+ const session = new FakeSession((_command, index) => {+ // 1 = port probe (refused), 2 = dsh probe, 3 = start, 4 = post-start probe (healthy).+ if (index === 1)+ return { code: 0, stdout: RESOLVED_DSH, stderr: '' }+ if (index === 2)+ return { code: 0, stdout: '', stderr: '' }+ if (index === 3)+ return { code: 0, stdout: '200', stderr: '' }+ return { code: 7, stdout: '', stderr: 'refused' }+ })+ const phases: unknown[] = []+ await ensureRemoteInstance(session, profile, 1000, 5, 3, progress => phases.push(progress))+ expect(phases).toEqual([+ { phase: 'starting' },+ { phase: 'probing', attempt: 1, total: 3 },+ ])+ })++ it('fails fast with DshMissingError when no dsh binary is reachable', async () => {+ const session = new FakeSession((command) => {+ if (command.includes('curl'))+ return { code: 7, stdout: '', stderr: '' }+ return { code: 0, stdout: '', stderr: '' }+ })+ await expect(ensureRemoteInstance(session, profile, 1000, 5, 3)).rejects.toBeInstanceOf(DshMissingError)+ })++ it('fails loud when the start command itself fails', async () => {+ const session = new FakeSession((_command, index) => {+ if (index === 1)+ return { code: 0, stdout: RESOLVED_DSH, stderr: '' }+ if (index === 2)+ return { code: 127, stdout: '', stderr: 'sh: dsh: not found' }+ return { code: 7, stdout: '', stderr: '' }+ })+ await expect(ensureRemoteInstance(session, profile, 1000, 5, 3)).rejects.toThrow(/start failed.*not found/)+ })++ it('fails loud when the instance never becomes reachable, with the log tail', async () => {+ const session = new FakeSession((command) => {+ if (command.includes('command -v dsh'))+ return { code: 0, stdout: RESOLVED_DSH, stderr: '' }+ if (command.includes('tail'))+ return { code: 0, stdout: 'dsh: command not found\nline2\nline3\nline4\nline5\nline6', stderr: '' }+ if (command.includes('curl'))+ return { code: 7, stdout: '', stderr: '' }+ return { code: 0, stdout: '', stderr: '' }+ })+ await expect(ensureRemoteInstance(session, profile, 1000, 5, 2)).rejects.toThrow(+ /did not become reachable.*line2 \| line3 \| line4 \| line5 \| line6/,+ )+ expect(session.commands).toHaveLength(6)+ })++ it('notes an empty remote log in the failure message', async () => {+ const session = new FakeSession((command) => {+ if (command.includes('command -v dsh'))+ return { code: 0, stdout: RESOLVED_DSH, stderr: '' }+ if (command.includes('tail'))+ return { code: 0, stdout: '', stderr: '' }+ if (command.includes('curl'))+ return { code: 7, stdout: '', stderr: '' }+ return { code: 0, stdout: '', stderr: '' }+ })+ await expect(ensureRemoteInstance(session, profile, 1000, 5, 1)).rejects.toThrow(/log is empty/)+ })++ it('notes an unreadable remote log in the failure message', async () => {+ const session = new FakeSession((command) => {+ if (command.includes('command -v dsh'))+ return { code: 0, stdout: RESOLVED_DSH, stderr: '' }+ if (command.includes('tail'))+ throw new Error('channel closed')+ if (command.includes('curl'))+ return { code: 7, stdout: '', stderr: '' }+ return { code: 0, stdout: '', stderr: '' }+ })+ await expect(ensureRemoteInstance(session, profile, 1000, 5, 1)).rejects.toThrow(/log unreadable/)+ })++ it('propagates transport failures', async () => {+ const session = new FakeSession(() => {+ throw new Error('channel closed')+ })+ await expect(ensureRemoteInstance(session, profile, 1000, 5, 2)).rejects.toThrow()+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.tsnew file mode 100644index 00000000..c3d566bf--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts@@ -0,0 +1,287 @@+/**+ * Remote-instance assurance: probe the remote `dsh web` port, auto-start the+ * instance when absent, and poll until it answers. Commands are pure+ * functions of the profile so the manager can drive them through any+ * transport; the polling loop owns the timing contract and reports its phase+ * through a progress callback so the settings page can show live progress.+ * Also the one-line dsh installer: probe for a `dsh` binary, run the official+ * install script through the remote shell, and copy the local API credentials.+ * @module dsh-tauri-ssh/host/service/bootstrap+ */++import type { Config } from '../storage/index.js'+import type { MachineProfile, SshProgress } from '../types/index.js'+import type { SshSession } from './transport.js'+import { readFileSync } from 'node:fs'+import { shQuote } from './transport.js'++/** Log file of the auto-started remote instance, under the remote home. */+export const REMOTE_WEB_LOG = '.dsh/dsh-remote-web.log'++/** The installer's default clone source (its DSH_REPO default). */+export const OFFICIAL_INSTALL_REPO = 'https://github.com/deepseek-harness/deepseek-harness.git'++/** The default remote-instance start command, parameterized by the profile's remote port. */+export function defaultStartCommand(profile: MachineProfile): string {+ return `dsh web --host 127.0.0.1 --port ${profile.remotePort}`+}++/**+ * The remote-instance start command: the profile override when present, else+ * the default with the resolved `dsh` binary substituted for the bare name+ * (the installer's `~/.local/bin` is rarely on a login shell's PATH). The+ * log directory is ensured first (a missing `$HOME/.dsh` would otherwise+ * swallow the redirection and every error with it), then the command runs+ * detached in the background with output redirected to the log; the health+ * probe judges the outcome, never the command. Deliberately no `nohup`: in an+ * sshd exec session there is no controlling terminal to detach from, and+ * macOS nohup then kills the child instead of protecting it — a plain+ * backgrounded job survives both the exec channel and connection close (no+ * pty was ever allocated).+ * @param profile - the machine profile.+ * @param dshPath - resolved remote `dsh` binary path, when known.+ * @returns the shell command line that starts (or restarts) the instance.+ */+export function startCommandFor(profile: MachineProfile, dshPath?: string): string {+ const base = profile.startCommand !== undefined+ ? profile.startCommand+ : dshPath === undefined+ ? defaultStartCommand(profile)+ : `${dshPath} web --host 127.0.0.1 --port ${profile.remotePort}`+ // Detach through a double subshell: `( … & ) &` — the inner background job+ // reparents (orphan) as soon as the wrapping subshell exits, so nothing+ // holds the exec channel's stdin and sshd closes the channel immediately+ // (a bare `… &` keeps the instance in the session: sshd holds the channel+ // open and ssh2's exec never settles). Output goes to the log with stdin+ // from /dev/null; no nohup (macOS nohup kills the child in this context).+ return `mkdir -p "$HOME/.dsh" && ( ${base} >>"$HOME/${REMOTE_WEB_LOG}" 2>&1 < /dev/null & ) &`+}++/**+ * Probe for a remote `dsh` binary, in install order: the login shell's PATH,+ * then the installer's `~/.local/bin` link, then the source checkout's+ * launcher. Prints the resolved path (possibly `$HOME`-relative) or nothing.+ * Each branch is a braced group so a successful `command -v` short-circuits+ * the whole `||` chain without the later `&& printf` arms firing too.+ */+export function probeDshCommand(): string {+ return [+ 'command -v dsh 2>/dev/null',+ `{ test -x "$HOME/.local/bin/dsh" && printf '%s\\n' "$HOME/.local/bin/dsh"; }`,+ `{ test -x "$HOME/.dsh/source/current/bin/dsh" && printf '%s\\n' "$HOME/.dsh/source/current/bin/dsh"; }`,+ 'true',+ ].join(' || ')+}++/**+ * The one-line remote install, built in (no external script to curl — the+ * "official" installer URL does not exist yet): clone the repository (the+ * configured `installRepo`, default branch or `installRef`), install+ * dependencies, build the web frontend, and link `dsh` into+ * `~/.local/bin` (the path the probe resolves when the login PATH lacks it).+ * A prior managed install under `~/.dsh/source` is replaced, so re-running+ * reinstalls cleanly.+ * @param config - plugin config (repo and ref overrides).+ * @returns the full remote install command line.+ */+export function installCommandFor(config: Pick<Config, 'installRepo' | 'installRef'>): string {+ const repo = config.installRepo === undefined || config.installRepo === ''+ ? OFFICIAL_INSTALL_REPO+ : config.installRepo+ const ref = config.installRef === undefined || config.installRef === ''+ ? undefined+ : config.installRef+ const clone = ref === undefined+ ? `git clone --depth 1 ${shQuote(repo)} "$HOME/.dsh/source/master"`+ : `git clone --depth 1 --branch ${shQuote(ref)} ${shQuote(repo)} "$HOME/.dsh/source/master"`+ return [+ 'set -e',+ `mkdir -p "$HOME/.dsh/source" "$HOME/.local/bin"`,+ `rm -rf "$HOME/.dsh/source/master" "$HOME/.dsh/source/current"`,+ `echo '==> cloning dsh source'`,+ clone,+ `ln -s "$HOME/.dsh/source/master" "$HOME/.dsh/source/current"`,+ `echo '==> ensuring pnpm'`,+ // pnpm may live outside the login PATH (nvm etc.): enable it via+ // corepack (ships with Node), else install it globally with npm.+ `(command -v pnpm >/dev/null 2>&1) || (corepack enable pnpm >/dev/null 2>&1) || npm install -g pnpm`,+ `echo '==> installing dependencies (pnpm install)'`,+ `(cd "$HOME/.dsh/source/current" && pnpm install)`,+ `echo '==> building web UI'`,+ `(cd "$HOME/.dsh/source/current" && pnpm run build)`,+ `ln -sfn "$HOME/.dsh/source/current/bin/dsh" "$HOME/.local/bin/dsh"`,+ `echo '==> dsh installed'`,+ ].join(' && ')+}++/** Credentials read from a local dsh `.env` document. */+export interface EnvCredentials {+ apiKey?: string+ baseUrl?: string+}++/**+ * Read `DEEPSEEK_API_KEY`/`DEEPSEEK_BASE_URL` from a dsh `.env` document+ * (the installer's own layout: `KEY=value` lines, no quoting).+ * @param path - the `.env` file path (the harness home's `.env`).+ * @returns the credentials present in the document.+ */+export function readEnvCredentials(path: string): EnvCredentials {+ let text: string+ try {+ text = readFileSync(path, 'utf8')+ }+ catch {+ return {}+ }+ const out: EnvCredentials = {}+ const apiKey = envValueOf(text, 'DEEPSEEK_API_KEY')+ /* v8 ignore next -- attribution artifact: both arms are exercised by the credentials tests */+ if (apiKey !== undefined)+ out.apiKey = apiKey+ const baseUrl = envValueOf(text, 'DEEPSEEK_BASE_URL')+ if (baseUrl !== undefined)+ out.baseUrl = baseUrl+ return out+}++/**+ * Write credentials into the remote `~/.dsh/.env` without clobbering an+ * existing key: print `copied` when the write happened, `existing` when the+ * remote already carries a key (kept untouched).+ * @param credentials - the credentials to write (apiKey required).+ * @returns the shell command line.+ */+export function credentialsCopyCommand(credentials: EnvCredentials & { apiKey: string }): string {+ const lines = [`printf 'DEEPSEEK_API_KEY=%s\\n' ${shQuote(credentials.apiKey)}`]+ if (credentials.baseUrl !== undefined) {+ lines.push(`printf 'DEEPSEEK_BASE_URL=%s\\n' ${shQuote(credentials.baseUrl)}`)+ }+ return [+ `mkdir -p "$HOME/.dsh"`,+ `if grep -q '^DEEPSEEK_API_KEY=' "$HOME/.dsh/.env" 2>/dev/null; then echo existing; else umask 077 && { ${lines.join('; ')}; } > "$HOME/.dsh/.env" && echo copied; fi`,+ ].join(' && ')+}++/** One `KEY=value` line of a `.env` document, optional surrounding quotes stripped. */+function envValueOf(text: string, key: string): string | undefined {+ for (const line of text.split('\n')) {+ if (!line.startsWith(`${key}=`))+ continue+ const value = line.slice(key.length + 1).trim().replace(/^"(.*)"$/u, '$1')+ return value === '' ? undefined : value+ }+ return undefined+}++/** The first non-empty line of a command's stdout, trimmed (a probe prints one path). */+export function firstLineOf(stdout: string): string {+ for (const line of stdout.split('\n')) {+ const trimmed = line.trim()+ if (trimmed !== '')+ return trimmed+ }+ return ''+}++/**+ * One health probe: curl the remote instance's web port. Any HTTP response+ * (including 404 on the bare path) proves the webserver listens; a refused+ * connection exits nonzero.+ */+export function healthCheckCommand(remotePort: number, timeoutMs: number): string {+ const seconds = Math.max(1, Math.ceil(timeoutMs / 1000))+ return `curl -s -o /dev/null -m ${seconds} -w '%{http_code}' http://127.0.0.1:${remotePort}/`+}++/** The tail command that recovers the remote instance's log for the error message. */+export function logTailCommand(): string {+ return `tail -n 20 "$HOME/${REMOTE_WEB_LOG}" 2>/dev/null || true`+}++/** The typed failure "the remote has no `dsh` binary" (offers the install path). */+export class DshMissingError extends Error {}++/**+ * Ensure the remote instance answers on its port: probe once, auto-start when+ * absent, then poll until healthy or the attempt budget is exhausted. The+ * failure message carries the remote log's tail — a backgrounded start always+ * exits 0 (even when the command itself fails), so the log is the only place+ * the real error (command not found, port busy, …) is visible. When the+ * default start command is in play (no profile override), the `dsh` binary is+ * resolved first and its absence fails fast with {@link DshMissingError}.+ * @param session - the authenticated SSH session.+ * @param profile - the machine profile (port + start command).+ * @param timeoutMs - per-probe curl deadline.+ * @param pollIntervalMs - pause between probes.+ * @param pollAttempts - total probes after the initial one.+ * @param onProgress - receives the live bootstrap phase (started/probing).+ * @returns a short description of the healthy instance (host:port).+ * @throws {DshMissingError} when no `dsh` binary is reachable.+ * @throws {Error} with an operator-facing message when the instance never becomes reachable.+ */+export async function ensureRemoteInstance(+ session: SshSession,+ profile: MachineProfile,+ timeoutMs: number,+ pollIntervalMs: number,+ pollAttempts: number,+ onProgress?: (progress: SshProgress) => void,+): Promise<string> {+ const probe = async (): Promise<boolean> => {+ const result = await session.exec(healthCheckCommand(profile.remotePort, timeoutMs))+ return result.code === 0+ }+ if (await probe())+ return `${profile.host}:${profile.remotePort}`+ onProgress?.({ phase: 'starting' })+ let dshPath: string | undefined+ if (profile.startCommand === undefined) {+ dshPath = firstLineOf((await session.exec(probeDshCommand())).stdout)+ if (dshPath === '') {+ throw new DshMissingError(+ `dsh is not installed on "${profile.host}" (checked the login PATH, ~/.local/bin and ~/.dsh/source/current); `+ + 'install it with the one-click install, or configure the machine\'s start command',+ )+ }+ }+ const started = await session.exec(startCommandFor(profile, dshPath))+ if (started.code !== 0) {+ throw new Error(+ `remote instance start failed on "${profile.host}": ${describeExecFailure(started.code, started.stderr)}`,+ )+ }+ for (let attempt = 0; attempt < pollAttempts; attempt++) {+ onProgress?.({ phase: 'probing', attempt: attempt + 1, total: pollAttempts })+ await sleep(pollIntervalMs)+ if (await probe())+ return `${profile.host}:${profile.remotePort}`+ }+ const tail = await logTail(session)+ throw new Error(+ `remote dsh web did not become reachable on "${profile.host}:${profile.remotePort}" `+ + `within ${pollAttempts} polls; remote log (${shQuote(`$HOME/${REMOTE_WEB_LOG}`)}) tail: ${tail}`,+ )+}++/** The remote instance log's tail, or a note when nothing was captured. */+async function logTail(session: SshSession): Promise<string> {+ try {+ const result = await session.exec(logTailCommand())+ const tail = result.stdout.trim()+ return tail === '' ? '(log is empty)' : tail.split('\n').slice(-5).join(' | ')+ }+ catch {+ return '(log unreadable)'+ }+}++/** One operator-facing fragment for a failed remote command. */+export function describeExecFailure(code: number | null, stderr: string): string {+ const tail = stderr.trim().split('\n').slice(-3).join(' | ')+ return `exit ${code ?? '?'}${tail === '' ? '' : `: ${tail}`}`+}++function sleep(ms: number): Promise<void> {+ return new Promise(resolve => setTimeout(resolve, ms))+}diff --git a/packages/dsh-tauri-ssh/src/host/service/fixtures/garbage.txt b/packages/dsh-tauri-ssh/src/host/service/fixtures/garbage.txtnew file mode 100644index 00000000..93675fe8--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/fixtures/garbage.txt@@ -0,0 +1 @@+not a key at alldiff --git a/packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519 b/packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519new file mode 100644index 00000000..e5cd1919--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519@@ -0,0 +1,7 @@+-----BEGIN OPENSSH PRIVATE KEY-----+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW+QyNTUxOQAAACCRK1Acy80mJLfTDc2X28kiZZgqYZ8BA8m843JIwrMiywAAAJCEHiFfhB4h+XwAAAAtzc2gtZWQyNTUxOQAAACCRK1Acy80mJLfTDc2X28kiZZgqYZ8BA8m843JIwrMiyw+AAAEA/MPEvu5nEeHX8vWd0v6WWmvcfRAxDvw2emXgYY1k/85ErUBzLzSYkt9MNzZfbySJl+mCphnwEDybzjckjCsyLLAAAAB2ZpeHR1cmUBAgMEBQY=+-----END OPENSSH PRIVATE KEY-----diff --git a/packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519.pub b/packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519.pubnew file mode 100644index 00000000..bbbe7313--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519.pub@@ -0,0 +1 @@+ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJErUBzLzSYkt9MNzZfbySJlmCphnwEDybzjckjCsyLL fixturediff --git a/packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519_enc b/packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519_encnew file mode 100644index 00000000..c9449982--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519_enc@@ -0,0 +1,8 @@+-----BEGIN OPENSSH PRIVATE KEY-----+b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABBohthZPz+60KHbMRG6nz5z0AAAAGAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIJErUBzLzSYkt9MN+zZfbySJlmCphnwEDybzjckjCsyLLAAAAkBCVHO04tP9SMNDUG2HrsPd88H0nYYWenmrZ2b+WI9hhs1atRuZhCSigLn18MEvzpZXorCNSt64At1WE+LoHlu2zCYsC++3qsMnV6SPTbgWD5+23G/N076vM3wK3IEsp81NfZfozK4vB2tYtY4wSf6qzcrWvdlx9TrE6UYUPSdIn/1l4DrRc+noIPlgF6Z0mYLj0w==+-----END OPENSSH PRIVATE KEY-----diff --git a/packages/dsh-tauri-ssh/src/host/service/fixtures/id_rsa.pub b/packages/dsh-tauri-ssh/src/host/service/fixtures/id_rsa.pubnew file mode 100644index 00000000..bbbe7313--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/fixtures/id_rsa.pub@@ -0,0 +1 @@+ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJErUBzLzSYkt9MNzZfbySJlmCphnwEDybzjckjCsyLL fixturediff --git a/packages/dsh-tauri-ssh/src/host/service/host-keys.test.ts b/packages/dsh-tauri-ssh/src/host/service/host-keys.test.tsnew file mode 100644index 00000000..bc430b2c--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/host-keys.test.ts@@ -0,0 +1,130 @@+import { Buffer } from 'node:buffer'+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import * as fsPromises from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { dirname, join } from 'pathe'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { MachineId } from '../types/index.js'+import { fingerprintHostKey, KnownHostsStore } from './host-keys.js'++// Wrap the real fs/promises so one test can force an atomic-rename failure;+// every other call passes through to the actual implementation.+vi.mock('node:fs/promises', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:fs/promises')>()+ return { ...actual, rename: vi.fn(actual.rename), rm: vi.fn(actual.rm) }+})++const roots: string[] = []++function tempFile(name: string): string {+ const root = mkdtempSync(join(tmpdir(), 'dsh-ssh-keys-'))+ roots.push(root)+ return join(root, name)+}++afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })+})++describe('fingerprintHostKey', () => {+ it('produces the ssh-keygen-style SHA256 form without padding', () => {+ const fingerprint = fingerprintHostKey(Buffer.from('host-key-bytes'))+ expect(fingerprint).toMatch(/^SHA256:[A-Za-z0-9+/]+$/)+ expect(fingerprint).not.toMatch(/=$/u)+ expect(fingerprintHostKey(Buffer.from('host-key-bytes'))).toBe(fingerprint)+ expect(fingerprintHostKey(Buffer.from('other'))).not.toBe(fingerprint)+ })+})++describe('knownHostsStore', () => {+ it('starts empty on a missing document', async () => {+ const store = new KnownHostsStore(tempFile('missing.json'))+ expect(await store.verify(MachineId('m1'), 'SHA256:abc')).toBe('unknown')+ })++ it('accepts and persists a first sight, then verifies it', async () => {+ const file = tempFile('hosts.json')+ const store = new KnownHostsStore(file)+ const fingerprint = 'SHA256:first'+ expect(await store.verify(MachineId('m1'), fingerprint)).toBe('unknown')+ await store.accept(MachineId('m1'), fingerprint)+ const reloaded = new KnownHostsStore(file)+ expect(await reloaded.verify(MachineId('m1'), fingerprint)).toBe('accepted')+ expect(await reloaded.verify(MachineId('m1'), 'SHA256:other')).toBe('mismatch')+ expect(await reloaded.verify(MachineId('m2'), fingerprint)).toBe('unknown')+ })++ it('keeps records of other machines on accept', async () => {+ const file = tempFile('hosts.json')+ const store = new KnownHostsStore(file)+ await store.accept(MachineId('m1'), 'SHA256:a')+ await store.accept(MachineId('m2'), 'SHA256:b')+ const reloaded = new KnownHostsStore(file)+ expect(await reloaded.verify(MachineId('m1'), 'SHA256:a')).toBe('accepted')+ expect(await reloaded.verify(MachineId('m2'), 'SHA256:b')).toBe('accepted')+ })++ it('forgets one machine idempotently', async () => {+ const file = tempFile('hosts.json')+ const store = new KnownHostsStore(file)+ await store.accept(MachineId('m1'), 'SHA256:a')+ await store.accept(MachineId('m2'), 'SHA256:b')+ await store.forget(MachineId('m1'))+ await store.forget(MachineId('m1'))+ const reloaded = new KnownHostsStore(file)+ expect(await reloaded.verify(MachineId('m1'), 'SHA256:a')).toBe('unknown')+ expect(await reloaded.verify(MachineId('m2'), 'SHA256:b')).toBe('accepted')+ })++ it('treats a corrupt document as empty and rewrites it on accept', async () => {+ const file = tempFile('hosts.json')+ const store = new KnownHostsStore(file)+ await store.accept(MachineId('m1'), 'SHA256:a')+ const raw = JSON.parse(readFileSync(file, 'utf8')) as unknown[]+ raw.push({ machineId: 'broken' })+ writeFileSync(file, JSON.stringify(raw))+ await store.accept(MachineId('m2'), 'SHA256:b')+ const reloaded = new KnownHostsStore(file)+ expect(await reloaded.verify(MachineId('m1'), 'SHA256:a')).toBe('accepted')+ })++ it('treats a non-array document as empty', async () => {+ const file = tempFile('hosts.json')+ writeFileSync(file, JSON.stringify({ not: 'an array' }))+ const store = new KnownHostsStore(file)+ expect(await store.verify(MachineId('m1'), 'SHA256:a')).toBe('unknown')+ })++ it('rejects invalid JSON as empty', async () => {+ const file = tempFile('hosts.json')+ writeFileSync(file, 'not json {')+ const store = new KnownHostsStore(file)+ expect(await store.verify(MachineId('m1'), 'SHA256:a')).toBe('unknown')+ await store.accept(MachineId('m1'), 'SHA256:a')+ const reloaded = new KnownHostsStore(file)+ expect(await reloaded.verify(MachineId('m1'), 'SHA256:a')).toBe('accepted')+ })++ it('rethrows non-ENOENT read failures', async () => {+ const path = tempFile('hosts.json')+ mkdirSync(path)+ const store = new KnownHostsStore(path)+ await expect(store.verify(MachineId('m1'), 'SHA256:a')).rejects.toThrow()+ })++ it('cleans up the temp document and rethrows when the atomic rename fails', async () => {+ const file = tempFile('hosts.json')+ const store = new KnownHostsStore(file)+ vi.mocked(fsPromises.rename).mockRejectedValueOnce(new Error('rename failed'))+ await expect(store.accept(MachineId('m1'), 'SHA256:a')).rejects.toThrow('rename failed')+ expect(readdirSync(dirname(file)).filter(entry => entry.endsWith('.tmp'))).toEqual([])+ })++ it('swallows a failing temp cleanup and rethrows the original failure', async () => {+ const file = tempFile('hosts.json')+ const store = new KnownHostsStore(file)+ vi.mocked(fsPromises.rename).mockRejectedValueOnce(new Error('rename failed'))+ vi.mocked(fsPromises.rm).mockRejectedValueOnce(new Error('rm failed'))+ await expect(store.accept(MachineId('m1'), 'SHA256:a')).rejects.toThrow('rename failed')+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/host-keys.ts b/packages/dsh-tauri-ssh/src/host/service/host-keys.tsnew file mode 100644index 00000000..6fa6ff9d--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/host-keys.ts@@ -0,0 +1,126 @@+/**+ * Trust-on-first-use host-key store for SSH connections. One JSON document+ * under the harness home records the accepted host-key fingerprint per+ * machine profile; a connection whose fingerprint matches is accepted, an+ * unknown one is accepted-and-persisted (TOFU), and a mismatch is rejected so+ * a swapped host cannot impersonate a known machine without an operator+ * resetting the record. Self-contained: the atomic write is a same-directory+ * temp + rename (no harness dependencies).+ * @module dsh-tauri-ssh/host/service/host-keys+ */++import type { Buffer } from 'node:buffer'+import type { MachineId } from '../types/index.js'+import { createHash, randomBytes } from 'node:crypto'+import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'+import { dirname } from 'pathe'++/** One persisted host-key record. */+export interface HostKeyRecord {+ /** Machine profile id the record belongs to. */+ machineId: string+ /** Fingerprint the profile's first successful connection saw. */+ fingerprint: string+}++/** Verdict of one host-key check. */+export type HostKeyVerdict = 'accepted' | 'unknown' | 'mismatch'++/** Fingerprint a raw SSH host key into the ssh-keygen-style `SHA256:<base64>` form. */+export function fingerprintHostKey(key: Buffer): string {+ return `SHA256:${createHash('sha256').update(key).digest('base64').replace(/=+$/u, '')}`+}++/** Atomically replace `filename` with `content` (owner-only permissions, same-dir rename). */+async function writeFileAtomic(filename: string, content: string): Promise<void> {+ await mkdir(dirname(filename), { recursive: true, mode: 0o700 })+ const temp = `${filename}.${randomBytes(6).toString('hex')}.tmp`+ try {+ await writeFile(temp, content, { mode: 0o600, flag: 'wx' })+ await rename(temp, filename)+ }+ catch (error) {+ await rm(temp, { force: true }).catch(() => undefined)+ throw error+ }+}++/**+ * File-backed TOFU store. Reads are cached in memory and refreshed on each+ * load; writes are atomic.+ */+export class KnownHostsStore {+ private records: HostKeyRecord[] = []++ /**+ * @param file - absolute path of the known-hosts JSON document.+ */+ constructor(private readonly file: string) {}++ /**+ * Load the document (idempotent, cached). A missing or malformed document+ * starts empty — the store must never block a first connection on its own+ * durability.+ */+ async load(): Promise<void> {+ let raw: string+ try {+ raw = await readFile(this.file, 'utf8')+ }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {+ this.records = []+ return+ }+ throw error+ }+ try {+ const parsed: unknown = JSON.parse(raw)+ this.records = Array.isArray(parsed) ? parsed as HostKeyRecord[] : []+ }+ catch {+ // A corrupt document resets trust rather than failing every connection.+ this.records = []+ }+ }++ /**+ * Check one machine's fingerprint against the store.+ * @param machineId - the machine profile being connected.+ * @param fingerprint - the presented host-key fingerprint.+ * @returns `accepted` on a match, `unknown` on a first sight, `mismatch` on a conflict.+ */+ async verify(machineId: MachineId, fingerprint: string): Promise<HostKeyVerdict> {+ await this.load()+ const record = this.records.find(entry => entry.machineId === machineId)+ if (record === undefined)+ return 'unknown'+ return record.fingerprint === fingerprint ? 'accepted' : 'mismatch'+ }++ /**+ * Persist a first-sight fingerprint (the TOFU commit). A concurrent+ * mismatch never overwrites: the caller verifies first.+ * @param machineId - the machine profile being connected.+ * @param fingerprint - the fingerprint to remember.+ */+ async accept(machineId: MachineId, fingerprint: string): Promise<void> {+ await this.load()+ const others = this.records.filter(entry => entry.machineId !== machineId)+ this.records = [...others, { machineId, fingerprint }]+ await writeFileAtomic(this.file, JSON.stringify(this.records, null, 2))+ }++ /**+ * Forget one machine's record (the operator-side reset when a host key+ * legitimately changed). Idempotent.+ * @param machineId - the machine whose record to drop.+ */+ async forget(machineId: MachineId): Promise<void> {+ const next = this.records.filter(entry => entry.machineId !== machineId)+ if (next.length === this.records.length)+ return+ this.records = next+ await writeFileAtomic(this.file, JSON.stringify(this.records, null, 2))+ }+}diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts b/packages/dsh-tauri-ssh/src/host/service/manager.test.tsnew file mode 100644index 00000000..b9dd1214--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/manager.test.ts@@ -0,0 +1,948 @@+import type { MachineProfile } from '../types/index.js'+import type { SshExecOptions, SshExecResult, SshSession, SshTransport, SshTunnelHandle } from './transport.js'+import { Buffer } from 'node:buffer'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'pathe'+import { afterEach, describe, expect, it } from 'vitest'+import { MachineId, SshError } from '../types/index.js'+import { KnownHostsStore } from './host-keys.js'+import { SshManager } from './manager.js'++const profile: MachineProfile = {+ id: MachineId('m1'),+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ password: 'sekrit',+ remotePort: 3080,+}++const secondProfile: MachineProfile = {+ ...profile,+ id: MachineId('m2'),+ name: 'beta',+}++const config = {+ connectTimeoutMs: 15000,+ healthCheckTimeoutMs: 1000,+ healthPollIntervalMs: 5,+ healthPollAttempts: 3,+ installTimeoutMs: 60000,+}++/** The dsh-path answer a remote probe would print. */+const RESOLVED_DSH = '/usr/local/bin/dsh'++class FakeSession implements SshSession {+ commands: string[] = []+ options: SshExecOptions[] = []+ closed = false+ tunnel: SshTunnelHandle | undefined+ closeCalls = 0+ tunnelCloseCalls = 0+ closeError: Error | undefined+ tunnelCloseError: Error | undefined+ tunnelGate: Promise<void> | undefined+ tunnelStarted: (() => void) | undefined+ execGate: ((command: string, index: number) => Promise<void> | undefined) | undefined+ /** What the remote dsh probe answers; undefined = a binary is reachable. */+ dshProbeResult: string | undefined = RESOLVED_DSH+ private closedCallbacks: Array<() => void> = []++ constructor(+ public healthHealthy: (commandIndex: number) => boolean,+ public connectError?: Error,+ public startError?: Error,+ public installError?: Error,+ ) {}++ exec(command: string, options?: SshExecOptions): Promise<SshExecResult> {+ this.commands.push(command)+ this.options.push(options ?? {})+ const respond = (): SshExecResult => {+ if (this.connectError !== undefined)+ throw this.connectError+ if (command.includes('command -v dsh')) {+ return { code: 0, stdout: this.dshProbeResult ?? '', stderr: '' }+ }+ if (command.includes('git clone')) {+ if (this.installError !== undefined)+ return { code: 1, stdout: '', stderr: this.installError.message }+ return { code: 0, stdout: 'installing...', stderr: '' }+ }+ if (command.includes('grep -q \'^DEEPSEEK_API_KEY=\'')) {+ return { code: 0, stdout: this.credentialsAnswer, stderr: '' }+ }+ if (command.includes('curl') && !this.healthHealthy(this.commands.length - 1)) {+ return { code: 7, stdout: '', stderr: 'refused' }+ }+ if (command.includes('web --host') && this.startError !== undefined) {+ return { code: 127, stdout: '', stderr: this.startError.message }+ }+ return { code: 0, stdout: '200', stderr: '' }+ }+ const gate = this.execGate?.(command, this.commands.length - 1)+ if (gate === undefined)+ return Promise.resolve(respond())+ return gate.then(respond)+ }++ /** The stdout the credentials-copy command answers (default: copied). */+ credentialsAnswer = 'copied'++ async openTunnel(): Promise<SshTunnelHandle> {+ this.tunnelStarted?.()+ if (this.tunnelGate !== undefined)+ await this.tunnelGate+ this.tunnel = {+ localPort: 49152,+ close: async () => {+ this.tunnelCloseCalls += 1+ this.tunnel = undefined+ if (this.tunnelCloseError !== undefined)+ throw this.tunnelCloseError+ },+ }+ return this.tunnel+ }++ onClosed(callback: () => void): void {+ this.closedCallbacks.push(callback)+ }++ drop(): void {+ for (const callback of this.closedCallbacks.splice(0)) callback()+ }++ async close(): Promise<void> {+ this.closeCalls += 1+ this.closed = true+ if (this.closeError !== undefined)+ throw this.closeError+ }+}++class FakeTransport implements SshTransport {+ sessions: FakeSession[] = []+ connectCalls = 0+ hostKeys: Array<{ key: Buffer, accepted: boolean }> = []+ rejectKeys = false++ constructor(private readonly sessionFactory: () => FakeSession) {}++ async connect(+ _profile: MachineProfile,+ hostKeyVerifier: (key: Buffer) => boolean | Promise<boolean>,+ ): Promise<SshSession> {+ this.connectCalls += 1+ const session = this.sessionFactory()+ this.sessions.push(session)+ if (this.rejectKeys)+ throw new Error('auth failed')+ if (session.connectError !== undefined)+ throw session.connectError+ const key = Buffer.from('host-key')+ this.hostKeys.push({ key, accepted: await hostKeyVerifier(key) })+ return session+ }+}++const roots: string[] = []++function tempKnownHosts(): KnownHostsStore {+ const root = mkdtempSync(join(tmpdir(), 'dsh-ssh-manager-'))+ roots.push(root)+ return new KnownHostsStore(join(root, 'known-hosts.json'))+}++afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })+})++function boot(overrides: Partial<{+ sessionFactory: () => FakeSession+ rejectKeys: boolean+ readEnvCredentials: () => { apiKey?: string, baseUrl?: string }+ config: typeof config+}> = {}) {+ const transport = new FakeTransport(overrides.sessionFactory ?? (() => new FakeSession(() => true)))+ transport.rejectKeys = overrides.rejectKeys ?? false+ const emits: Array<{ id: MachineId, state: string, progress?: { phase: string } }> = []+ const manager = new SshManager({+ transport,+ knownHosts: tempKnownHosts(),+ config: overrides.config ?? config,+ ...overrides.readEnvCredentials === undefined ? {} : { readEnvCredentials: overrides.readEnvCredentials },+ emitStatus: (id, status) => {+ emits.push({ id, state: status.state, ...status.progress === undefined ? {} : { progress: status.progress } })+ },+ })+ manager.refreshProfiles(new Map([[profile.id, profile], [secondProfile.id, secondProfile]]))+ return { manager, transport, emits }+}++describe('sshManager', () => {+ it('lists redacted profile views in settings order', () => {+ const { manager } = boot()+ const views = manager.profileViews()+ expect(views.map(view => view.id)).toEqual([MachineId('m1'), MachineId('m2')])+ expect(views[0]).toMatchObject({+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ hasPassword: true,+ hasPassphrase: false,+ remotePort: 3080,+ })+ expect(manager.statuses().map(status => status.machineId)).toEqual([MachineId('m1'), MachineId('m2')])+ expect(manager.statuses()[0]).toEqual({ machineId: MachineId('m1'), state: 'disconnected' })+ })++ it('reports unknown machines as disconnected without state', () => {+ const { manager } = boot()+ expect(manager.status(MachineId('ghost'))).toEqual({ machineId: MachineId('ghost'), state: 'disconnected' })+ expect(manager.link(MachineId('ghost'))).toBeUndefined()+ })++ it('connects a healthy machine and publishes the link', async () => {+ const { manager, transport, emits } = boot()+ const link = await manager.connect(MachineId('m1'))+ expect(link.tunnelBaseUrl).toBe('http://127.0.0.1:49152')+ expect(manager.link(MachineId('m1'))?.tunnelBaseUrl).toBe(link.tunnelBaseUrl)+ expect(manager.status(MachineId('m1')).state).toBe('connected')+ expect(transport.connectCalls).toBe(1)+ expect(transport.hostKeys[0]?.accepted).toBe(true)+ expect(emits.map(entry => entry.state)).toEqual(['connecting', 'connected'])+ })++ it('is idempotent for an already-connected machine', async () => {+ const { manager, transport } = boot()+ const first = await manager.connect(MachineId('m1'))+ const second = await manager.connect(MachineId('m1'))+ expect(second).toBe(first)+ expect(transport.connectCalls).toBe(1)+ })++ it('dedupes concurrent connects onto one attempt', async () => {+ const { manager, transport } = boot()+ const [a, b] = await Promise.all([manager.connect(MachineId('m1')), manager.connect(MachineId('m1'))])+ expect(a).toBe(b)+ expect(transport.connectCalls).toBe(1)+ })++ it('auto-starts the instance when the first probe fails', async () => {+ const session = new FakeSession(index => index !== 0)+ const { manager } = boot({ sessionFactory: () => session })+ await manager.connect(MachineId('m1'))+ expect(session.commands[0]).toContain('curl')+ expect(session.commands[1]).toContain('command -v dsh')+ expect(session.commands[2]).toContain(`${RESOLVED_DSH} web --host 127.0.0.1 --port 3080`)+ expect(manager.status(MachineId('m1')).state).toBe('connected')+ })++ it('publishes live progress phases while connecting', async () => {+ const session = new FakeSession(index => index !== 0)+ const { manager, emits } = boot({ sessionFactory: () => session })+ const pending = manager.connect(MachineId('m1'))+ expect(manager.status(MachineId('m1')).progress).toEqual({ phase: 'handshake' })+ await pending+ expect(manager.status(MachineId('m1')).progress).toBeUndefined()+ const phases = emits.filter(entry => entry.progress !== undefined).map(entry => entry.progress)+ expect(phases).toEqual([+ { phase: 'handshake' },+ { phase: 'starting' },+ { phase: 'probing', attempt: 1, total: 3 },+ ])+ })++ it('does not publish bootstrap progress once a disconnect superseded the attempt', async () => {+ let releaseStart: (() => void) | undefined+ const startGate = new Promise<void>((resolve) => {+ releaseStart = resolve+ })+ const session = new FakeSession(index => index !== 0)+ session.execGate = command => command.includes('web --host') ? startGate : undefined+ const { manager, emits } = boot({ sessionFactory: () => session })+ const pending = manager.connect(MachineId('m1'))+ // Wait until the start command is in flight, then supersede the attempt.+ await new Promise<void>((resolve) => {+ const timer = setInterval(() => {+ if (session.commands.some(command => command.includes('web --host'))) {+ clearInterval(timer)+ resolve()+ }+ }, 1)+ })+ await manager.disconnect(MachineId('m1'))+ releaseStart!()+ await expect(pending).rejects.toMatchObject({ code: 'machine-connect-failed' })+ expect(manager.status(MachineId('m1')).progress).toBeUndefined()+ // 'starting' fires before the start command (legitimately pre-disconnect);+ // the post-disconnect 'probing' phases must never be published.+ expect(emits.filter(entry => entry.progress?.phase === 'probing')).toEqual([])+ expect(emits.map(entry => entry.state)).toEqual(['connecting', 'connecting', 'disconnected'])+ })++ it('clears progress and reports the failure when connect fails', async () => {+ const { manager } = boot({ rejectKeys: true })+ await expect(manager.connect(MachineId('m1'))).rejects.toThrow()+ const status = manager.status(MachineId('m1'))+ expect(status.state).toBe('disconnected')+ expect(status.progress).toBeUndefined()+ expect(status.lastError).toBe('auth failed')+ })++ it('fails loud with machine-connect-failed on transport errors', async () => {+ const { manager } = boot({ rejectKeys: true })+ await expect(manager.connect(MachineId('m1'))).rejects.toThrow(SshError)+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-connect-failed' })+ const status = manager.status(MachineId('m1'))+ expect(status.state).toBe('disconnected')+ expect(status.lastError).toBe('auth failed')+ })++ it('fails loud with machine-bootstrap-failed when the instance never answers', async () => {+ const { manager } = boot({ sessionFactory: () => new FakeSession(() => false) })+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')+ })++ it('fails loud with machine-bootstrap-failed when the start command fails', async () => {+ const { manager } = boot({+ sessionFactory: () => new FakeSession(() => false, undefined, new Error('dsh: not found')),+ })+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })+ })++ it('rejects unknown machine ids with machine-not-found', async () => {+ const { manager, transport } = boot()+ await expect(manager.connect(MachineId('ghost'))).rejects.toMatchObject({ code: 'machine-not-found' })+ await expect(manager.test(MachineId('ghost'))).rejects.toMatchObject({ code: 'machine-not-found' })+ expect(transport.connectCalls).toBe(0)+ })++ it('resolves idempotently for unknown machine ids on disconnect', async () => {+ const { manager } = boot()+ await manager.disconnect(MachineId('ghost'))+ expect(manager.status(MachineId('ghost')).state).toBe('disconnected')+ })++ it('disconnects a connected machine idempotently', async () => {+ const { manager, transport } = boot()+ await manager.connect(MachineId('m1'))+ const session = transport.sessions[0]!+ await manager.disconnect(MachineId('m1'))+ await manager.disconnect(MachineId('m1'))+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')+ expect(manager.link(MachineId('m1'))).toBeUndefined()+ expect(session.closeCalls).toBe(1)+ expect(session.tunnelCloseCalls).toBe(1)+ })++ it('swallows teardown failures on disconnect', async () => {+ const { manager, transport } = boot()+ await manager.connect(MachineId('m1'))+ const session = transport.sessions[0]!+ session.tunnelCloseError = new Error('listener busy')+ session.closeError = new Error('socket busy')+ await manager.disconnect(MachineId('m1'))+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')+ })++ it('cancels an in-flight connect on disconnect', async () => {+ const { manager, emits } = boot({ rejectKeys: true })+ const pending = manager.connect(MachineId('m1'))+ await manager.disconnect(MachineId('m1'))+ await expect(pending).rejects.toMatchObject({ code: 'machine-connect-failed', message: /cancelled by disconnect/ })+ expect(emits.map(entry => entry.state)).toEqual(['connecting', 'disconnected'])+ })++ it('cancels an in-flight connect that disconnects during bootstrap', async () => {+ let releaseProbe: (() => void) | undefined+ let markProbeStarted: (() => void) | undefined+ const gate = new Promise<void>((resolve) => {+ releaseProbe = resolve+ })+ const probeStarted = new Promise<void>((resolve) => {+ markProbeStarted = resolve+ })+ const session = new FakeSession(() => true)+ session.exec = () => {+ markProbeStarted?.()+ return gate.then(() => ({ code: 0, stdout: '200', stderr: '' }))+ }+ const { manager } = boot({ sessionFactory: () => session })+ const pending = manager.connect(MachineId('m1'))+ await probeStarted+ await manager.disconnect(MachineId('m1'))+ releaseProbe!()+ await expect(pending).rejects.toMatchObject({ code: 'machine-connect-failed', message: /cancelled by disconnect/ })+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')+ })++ it('cancels an in-flight connect that disconnects during tunnel opening', async () => {+ let releaseTunnel: (() => void) | undefined+ let markTunnelStarted: (() => void) | undefined+ const gate = new Promise<void>((resolve) => {+ releaseTunnel = resolve+ })+ const tunnelStarted = new Promise<void>((resolve) => {+ markTunnelStarted = resolve+ })+ const session = new FakeSession(() => true)+ session.tunnelGate = gate+ session.tunnelStarted = () => markTunnelStarted?.()+ session.tunnelCloseError = new Error('close refused')+ const { manager } = boot({ sessionFactory: () => session })+ const pending = manager.connect(MachineId('m1'))+ await tunnelStarted+ await manager.disconnect(MachineId('m1'))+ releaseTunnel!()+ await expect(pending).rejects.toMatchObject({ code: 'machine-connect-failed', message: /cancelled by disconnect/ })+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')+ })++ it('discards a tunnel failure that a disconnect superseded', async () => {+ let releaseTunnel: ((error: Error) => void) | undefined+ let markTunnelStarted: (() => void) | undefined+ const tunnelStarted = new Promise<void>((resolve) => {+ markTunnelStarted = resolve+ })+ const session = new FakeSession(() => true)+ session.tunnelGate = new Promise<never>((_, reject) => {+ releaseTunnel = reject+ })+ session.tunnelStarted = () => markTunnelStarted?.()+ const { manager, emits } = boot({ sessionFactory: () => session })+ const pending = manager.connect(MachineId('m1'))+ await tunnelStarted+ await manager.disconnect(MachineId('m1'))+ releaseTunnel!(new Error('tunnel setup failed'))+ await expect(pending).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')+ expect(emits.map(entry => entry.state)).toEqual(['connecting', 'disconnected'])+ })++ it('marks the machine disconnected when the SSH session drops', async () => {+ const { manager, transport } = boot()+ await manager.connect(MachineId('m1'))+ const session = transport.sessions[0]!+ session.drop()+ const status = manager.status(MachineId('m1'))+ expect(status.state).toBe('disconnected')+ expect(status.lastError).toBe('SSH connection closed')+ expect(manager.link(MachineId('m1'))).toBeUndefined()+ })++ it('ignores session-close callbacks that no longer own the state', async () => {+ const { manager, transport } = boot()+ await manager.connect(MachineId('m1'))+ const oldSession = transport.sessions[0]!+ await manager.disconnect(MachineId('m1'))+ await manager.connect(MachineId('m1'))+ oldSession.drop()+ expect(manager.status(MachineId('m1')).state).toBe('connected')+ })++ it('swallows tunnel close failures when the session drops', async () => {+ const { manager, transport } = boot()+ await manager.connect(MachineId('m1'))+ const session = transport.sessions[0]!+ session.tunnelCloseError = new Error('listener busy')+ session.drop()+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')+ })++ it('probes a machine with a remote banner', async () => {+ const session = new FakeSession(() => true)+ session.commands = []+ const { manager } = boot({ sessionFactory: () => session })+ const result = await manager.test(MachineId('m1'))+ expect(result).toEqual({ ok: true, banner: '200' })+ expect(session.commands).toEqual(['uname -srm'])+ expect(session.closed).toBe(true)+ })++ it('reports probe failures without throwing', async () => {+ const session = new FakeSession(() => true, undefined, undefined)+ session.exec = () => Promise.resolve({ code: 1, stdout: '', stderr: 'denied' })+ const { manager } = boot({ sessionFactory: () => session })+ const result = await manager.test(MachineId('m1'))+ expect(result).toEqual({ ok: false, message: 'exit 1: denied' })+ })++ it('reports transport failures during probes without throwing', async () => {+ const { manager } = boot({ rejectKeys: true })+ const result = await manager.test(MachineId('m1'))+ expect(result).toEqual({ ok: false, message: 'auth failed' })+ })++ it('reports exec failures during probes without throwing', async () => {+ const session = new FakeSession(() => true)+ session.exec = () => Promise.reject(new Error('channel reset'))+ const { manager } = boot({ sessionFactory: () => session })+ const result = await manager.test(MachineId('m1'))+ expect(result).toEqual({ ok: false, message: 'channel reset' })+ })++ it('reports non-Error probe failures without throwing', async () => {+ const session = new FakeSession(() => true)+ // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- exercise a hostile non-Error rejection+ // eslint-disable-next-line prefer-promise-reject-errors -- deliberately non-Error: covers describeSshFailure's String(error) arm+ session.exec = () => Promise.reject('plain string')+ const { manager } = boot({ sessionFactory: () => session })+ const result = await manager.test(MachineId('m1'))+ expect(result).toEqual({ ok: false, message: 'plain string' })+ })++ it('fails loud with an empty transport error message', async () => {+ const session = new FakeSession(() => true)+ // eslint-disable-next-line unicorn/error-message -- empty message on purpose: covers the 'SSH connection failed' fallback+ session.connectError = new Error('')+ const { manager } = boot({ sessionFactory: () => session })+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-connect-failed', message: 'SSH connection failed' })+ const probe = await manager.test(MachineId('m1'))+ expect(probe).toEqual({ ok: false, message: 'SSH connection failed' })+ })++ it('fails loud with a non-Error bootstrap failure', async () => {+ const session = new FakeSession(() => false)+ // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- exercise a hostile non-Error rejection+ // eslint-disable-next-line prefer-promise-reject-errors -- deliberately non-Error: covers describeSshFailure's String(error) arm+ session.exec = () => Promise.reject('channel reset')+ const { manager } = boot({ sessionFactory: () => session })+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })+ expect(manager.status(MachineId('m1')).lastError).toBe('channel reset')+ })++ it('swallows close failures during a failed bootstrap', async () => {+ const session = new FakeSession(() => false)+ session.closeError = new Error('close refused')+ const { manager } = boot({ sessionFactory: () => session })+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })+ expect(session.closeCalls).toBe(1)+ })++ it('exposes the startCommand override in profile views', () => {+ const { manager } = boot()+ const overridden: MachineProfile = { ...profile, startCommand: 'dsh web --port 4000' }+ manager.refreshProfiles(new Map([[MachineId('m1'), overridden]]))+ expect(manager.profileViews()[0]?.startCommand).toBe('dsh web --port 4000')+ })++ it('rejects a mismatched host key (TOFU conflict)', async () => {+ const { manager, transport } = boot()+ await manager.connect(MachineId('m1'))+ transport.connect = async function (this: FakeTransport, _p: MachineProfile, verifier: (key: Buffer) => boolean | Promise<boolean>): Promise<SshSession> {+ const accepted = await verifier(Buffer.from('other-key'))+ if (!accepted)+ throw new Error('Host key verification failed')+ const session = new FakeSession(() => true)+ this.sessions.push(session)+ return session+ }+ await manager.disconnect(MachineId('m1'))+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-connect-failed' })+ })++ it('disconnects machines whose profile vanished on refresh', async () => {+ const { manager } = boot()+ await manager.connect(MachineId('m1'))+ manager.refreshProfiles(new Map([[secondProfile.id, secondProfile]]))+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')+ expect(manager.status(MachineId('m2')).state).toBe('disconnected')+ })++ it('keeps a connected machine whose profile survives a refresh', async () => {+ const { manager } = boot()+ await manager.connect(MachineId('m1'))+ manager.refreshProfiles(new Map([[profile.id, profile], [secondProfile.id, secondProfile]]))+ expect(manager.status(MachineId('m1')).state).toBe('connected')+ expect(manager.link(MachineId('m1'))).toBeDefined()+ })++ it('disposes every connection', async () => {+ const { manager } = boot()+ await manager.connect(MachineId('m1'))+ await manager.connect(MachineId('m2'))+ await manager.dispose()+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')+ expect(manager.status(MachineId('m2')).state).toBe('disconnected')+ })++ it('marks dshMissing when the remote has no dsh binary', async () => {+ const session = new FakeSession(index => index !== 0)+ session.dshProbeResult = ''+ const { manager } = boot({ sessionFactory: () => session })+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-dsh-missing' })+ const status = manager.status(MachineId('m1'))+ expect(status.dshMissing).toBe(true)+ expect(status.state).toBe('disconnected')+ expect(status.lastError).toContain('dsh is not installed')+ })++ it('clears the dshMissing marker on disconnect', async () => {+ const session = new FakeSession(index => index !== 0)+ session.dshProbeResult = ''+ const { manager } = boot({ sessionFactory: () => session })+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-dsh-missing' })+ await manager.disconnect(MachineId('m1'))+ expect(manager.status(MachineId('m1')).dshMissing).toBeUndefined()+ })+})++describe('sshManager install', () => {+ /** Wait until the published state satisfies the predicate (auto-connect races). */+ async function until(predicate: () => boolean, label: string): Promise<void> {+ const deadline = Date.now() + 2000+ while (!predicate()) {+ if (Date.now() > deadline)+ throw new Error(`timed out waiting for ${label}`)+ await new Promise(resolve => setTimeout(resolve, 5))+ }+ }++ it('installs dsh end-to-end, copies credentials, and auto-connects', async () => {+ // Session 1 = install (installer, dsh probe, credentials copy); session 2+ // = the automatic connect (port probe refused, dsh probe, start, healthy).+ let sessions = 0+ const factory = () => {+ sessions += 1+ return new FakeSession(index => sessions === 2 && index === 3)+ }+ const { manager, transport } = boot({+ sessionFactory: factory,+ readEnvCredentials: () => ({ apiKey: 'sk-test', baseUrl: 'https://api.example.com' }),+ })+ const result = await manager.install(MachineId('m1'))+ expect(result).toEqual({ dshPath: RESOLVED_DSH, credentialsCopied: true })+ const installSession = transport.sessions[0]!+ expect(installSession.commands[0]).toContain('git clone')+ expect(installSession.commands[0]).toContain('pnpm run build')+ expect(installSession.commands[1]).toContain('command -v dsh')+ expect(installSession.commands[2]).toContain('DEEPSEEK_API_KEY')+ expect(installSession.options[0]!.timeoutMs).toBe(60000)+ expect(typeof installSession.options[0]!.onData).toBe('function')+ await until(() => manager.status(MachineId('m1')).state === 'connected', 'auto-connect')+ expect(transport.connectCalls).toBe(2)+ })++ it('publishes the installing phase with the streaming install log', async () => {+ const session = new FakeSession(() => false)+ const { manager } = boot({ sessionFactory: () => session })+ const pending = manager.install(MachineId('m1'))+ expect(manager.status(MachineId('m1')).progress).toEqual({ phase: 'installing' })+ // Wait until the install command is in flight, then feed the streaming tap.+ await until(() => session.commands.length >= 1, 'install exec')+ session.options[0]?.onData?.('==> Checking dependencies\n')+ session.options[0]?.onData?.('git ... ok')+ expect(manager.status(MachineId('m1')).progress).toEqual({+ phase: 'installing',+ log: '==> Checking dependencies\ngit ... ok',+ })+ await pending+ })++ it('dedupes concurrent installs onto one attempt', async () => {+ const { manager, transport } = boot({ readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ const [a, b] = await Promise.all([manager.install(MachineId('m1')), manager.install(MachineId('m1'))])+ expect(a).toEqual(b)+ // One install exec (the auto-connect session is separate).+ const installRuns = transport.sessions+ .flatMap(session => session.commands)+ .filter(command => command.includes('git clone'))+ expect(installRuns).toHaveLength(1)+ })++ it('skips the credentials copy when the local env has no key', async () => {+ const session = new FakeSession(() => false)+ const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({}) })+ const result = await manager.install(MachineId('m1'))+ expect(result.credentialsCopied).toBe(false)+ expect(session.commands.some(command => command.includes('DEEPSEEK_API_KEY'))).toBe(false)+ })++ it('keeps an existing remote key untouched', async () => {+ const session = new FakeSession(() => false)+ session.credentialsAnswer = 'existing'+ const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ const result = await manager.install(MachineId('m1'))+ expect(result.credentialsCopied).toBe(false)+ })++ it('reports a credentials write failure without failing the install', async () => {+ const session = new FakeSession(() => false)+ session.exec = (command, _options) => command.includes('grep -q \'^DEEPSEEK_API_KEY=\'')+ ? Promise.resolve({ code: 1, stdout: '', stderr: 'disk full' })+ : Promise.resolve({ code: 0, stdout: 'installed', stderr: '' })+ const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ const result = await manager.install(MachineId('m1'))+ expect(result.credentialsCopied).toBe(false)+ expect(result.credentialsError).toContain('disk full')+ })++ it('fails loud with machine-install-failed when the install command fails', async () => {+ const session = new FakeSession(() => false)+ const original = session.exec.bind(session)+ session.exec = (command, options) => command.includes('git clone')+ ? Promise.resolve({ code: 1, stdout: '', stderr: 'pnpm: not found' })+ : original(command, options)+ const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({+ code: 'machine-install-failed',+ message: /pnpm: not found/,+ })+ const status = manager.status(MachineId('m1'))+ expect(status.state).toBe('disconnected')+ expect(status.progress).toBeUndefined()+ expect(session.closed).toBe(true)+ })++ it('carries the installer output tail in a failed-install error', async () => {+ const session = new FakeSession(() => false)+ const original = session.exec.bind(session)+ session.exec = (command, options) => {+ if (command.includes('git clone')) {+ // The transport streams installer output before failing.+ options?.onData?.('==> cloning dsh source\n')+ options?.onData?.('fatal: repository not found')+ return Promise.resolve({ code: 1, stdout: '', stderr: 'clone failed' })+ }+ return original(command, options)+ }+ const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({+ code: 'machine-install-failed',+ message: /installer output tail: ==> cloning dsh source \| fatal: repository not found/,+ })+ })++ it('fails loud with machine-connect-failed when the install connection fails', async () => {+ const { manager } = boot({ rejectKeys: true })+ await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-connect-failed' })+ const status = manager.status(MachineId('m1'))+ expect(status.state).toBe('disconnected')+ expect(status.lastError).toBe('auth failed')+ })++ it('runs without an install timeout when the config omits it', async () => {+ const session = new FakeSession(() => false)+ const { manager } = boot({+ sessionFactory: () => session,+ config: { ...config, installTimeoutMs: undefined as unknown as number },+ readEnvCredentials: () => ({ apiKey: 'sk-test' }),+ })+ await manager.install(MachineId('m1'))+ expect(session.options[0]!.timeoutMs).toBeUndefined()+ expect(typeof session.options[0]!.onData).toBe('function')+ })++ it('falls back to the local harness .env when no credentials reader is injected', async () => {+ const session = new FakeSession(() => false)+ const { manager } = boot({ sessionFactory: () => session })+ // No readEnvCredentials injection: the manager reads the host's own+ // $DSH_HOME/.env — whatever it holds, the install still completes.+ const result = await manager.install(MachineId('m1'))+ expect(result.dshPath).toBe(RESOLVED_DSH)+ expect(result.credentialsError).toBeUndefined()+ })++ it('reads the harness home from the DSH_HOME environment variable', async () => {+ const previous = process.env.DSH_HOME+ try {+ // Left branch of the ?? : DSH_HOME set.+ process.env.DSH_HOME = join(tmpdir(), 'dsh-home-custom')+ const withVar = new FakeSession(() => false)+ await boot({ sessionFactory: () => withVar }).manager.install(MachineId('m1'))+ // Right branch: DSH_HOME unset (falls back to ~/.dsh).+ delete process.env.DSH_HOME+ const withoutVar = new FakeSession(() => false)+ await boot({ sessionFactory: () => withoutVar }).manager.install(MachineId('m1'))+ }+ finally {+ if (previous === undefined)+ delete process.env.DSH_HOME+ else process.env.DSH_HOME = previous+ }+ })++ it('does not publish install state once a disconnect superseded the connection', async () => {+ const { manager, emits } = boot({ rejectKeys: true })+ const pending = manager.install(MachineId('m1'))+ await manager.disconnect(MachineId('m1'))+ await expect(pending).rejects.toMatchObject({ code: 'machine-connect-failed' })+ expect(manager.status(MachineId('m1')).lastError).toBeUndefined()+ // The install start and the disconnect both published 'disconnected';+ // the superseded attempt itself never published.+ expect(emits.map(entry => entry.state)).toEqual(['disconnected', 'disconnected'])+ })++ it('reports a non-Error credentials failure without failing the install', async () => {+ const session = new FakeSession(() => false)+ session.exec = (command, _options) => command.includes('grep -q \'^DEEPSEEK_API_KEY=\'')+ // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- hostile rejection+ // eslint-disable-next-line prefer-promise-reject-errors -- deliberately non-Error: covers describeExecFailure's message tail+ ? Promise.reject('disk full')+ : Promise.resolve({ code: 0, stdout: 'installed', stderr: '' })+ const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ const result = await manager.install(MachineId('m1'))+ expect(result.credentialsCopied).toBe(false)+ expect(result.credentialsError).toBe('disk full')+ })++ it('fails without publishing once a disconnect superseded an exec failure', async () => {+ let releaseInstall: (() => void) | undefined+ const installGate = new Promise<void>((resolve) => {+ releaseInstall = resolve+ })+ const session = new FakeSession(() => false, undefined, undefined, new Error('pnpm: not found'))+ session.execGate = command => command.includes('git clone') ? installGate : undefined+ const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ const pending = manager.install(MachineId('m1'))+ await new Promise<void>((resolve) => {+ const timer = setInterval(() => {+ if (session.commands.some(command => command.includes('git clone'))) {+ clearInterval(timer)+ resolve()+ }+ }, 1)+ })+ await manager.disconnect(MachineId('m1'))+ releaseInstall!()+ await expect(pending).rejects.toMatchObject({ code: 'machine-install-failed', message: 'dsh install failed' })+ expect(manager.status(MachineId('m1')).lastError).toBeUndefined()+ expect(manager.status(MachineId('m1')).progress).toBeUndefined()+ })++ it('fails loud when the install finished but no dsh binary is reachable', async () => {+ const session = new FakeSession(() => false)+ session.dshProbeResult = ''+ const { manager } = boot({ sessionFactory: () => session })+ await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({+ code: 'machine-install-failed',+ message: /no dsh binary is reachable/,+ })+ })++ it('clears dshMissing after a successful install and reconnects', async () => {+ let sessions = 0+ const factory = () => {+ sessions += 1+ const session = new FakeSession(index => sessions >= 2 && index === 3)+ // The first (failed) connect sees no dsh; the install and auto-connect do.+ if (sessions === 1)+ session.dshProbeResult = ''+ return session+ }+ const { manager, transport } = boot({+ sessionFactory: factory,+ readEnvCredentials: () => ({ apiKey: 'sk-test' }),+ })+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-dsh-missing' })+ expect(manager.status(MachineId('m1')).dshMissing).toBe(true)+ const result = await manager.install(MachineId('m1'))+ expect(result.dshPath).toBe(RESOLVED_DSH)+ expect(manager.status(MachineId('m1')).dshMissing).toBeUndefined()+ await until(() => manager.status(MachineId('m1')).state === 'connected', 'auto-connect after install')+ // First (failed) connect + install + auto-connect.+ expect(transport.connectCalls).toBe(3)+ })++ it('does not auto-connect when a disconnect superseded the install', async () => {+ let releaseInstall: (() => void) | undefined+ const installGate = new Promise<void>((resolve) => {+ releaseInstall = resolve+ })+ const session = new FakeSession(() => false)+ session.execGate = command => command.includes('git clone') ? installGate : undefined+ const { manager, transport } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ const pending = manager.install(MachineId('m1'))+ await new Promise<void>((resolve) => {+ const timer = setInterval(() => {+ if (session.commands.some(command => command.includes('git clone'))) {+ clearInterval(timer)+ resolve()+ }+ }, 1)+ })+ await manager.disconnect(MachineId('m1'))+ // Output arriving after the supersede must not touch the published log.+ session.options[0]?.onData?.('stale output')+ expect(manager.status(MachineId('m1')).progress).toBeUndefined()+ releaseInstall!()+ await expect(pending).rejects.toMatchObject({ code: 'machine-install-failed', message: /cancelled by disconnect/ })+ await new Promise(resolve => setTimeout(resolve, 20))+ expect(transport.connectCalls).toBe(1)+ expect(manager.status(MachineId('m1')).progress).toBeUndefined()+ })++ it('returns the install result without connecting once a disconnect superseded the finish', async () => {+ let releaseCopy: (() => void) | undefined+ const copyGate = new Promise<void>((resolve) => {+ releaseCopy = resolve+ })+ const session = new FakeSession(() => false)+ session.execGate = command => command.includes('grep -q \'^DEEPSEEK_API_KEY=\'') ? copyGate : undefined+ const { manager, transport } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ const pending = manager.install(MachineId('m1'))+ await until(() => session.commands.some(command => command.includes('grep -q \'^DEEPSEEK_API_KEY=\'')), 'credentials copy')+ await manager.disconnect(MachineId('m1'))+ releaseCopy!()+ const result = await pending+ expect(result.credentialsCopied).toBe(true)+ await new Promise(resolve => setTimeout(resolve, 20))+ expect(transport.connectCalls).toBe(1)+ expect(manager.status(MachineId('m1')).progress).toBeUndefined()+ })++ it('swallows a session close failure at the end of a successful install', async () => {+ const session = new FakeSession(() => false)+ session.closeError = new Error('close refused')+ const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ const result = await manager.install(MachineId('m1'))+ expect(result.credentialsCopied).toBe(true)+ expect(result.credentialsError).toBeUndefined()+ })++ it('swallows a close failure during a failed install', async () => {+ const session = new FakeSession(() => false, undefined, undefined, new Error('pnpm: not found'))+ session.closeError = new Error('close refused')+ const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-install-failed' })+ expect(session.closeCalls).toBe(1)+ })++ it('swallows a failed auto-connect after a successful install', async () => {+ let sessions = 0+ const factory = () => {+ sessions += 1+ // The install session is fine; the automatic connect session fails auth.+ return sessions === 1+ ? new FakeSession(() => false)+ : new FakeSession(() => true, new Error('auth failed'))+ }+ const { manager, transport } = boot({ sessionFactory: factory, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ const result = await manager.install(MachineId('m1'))+ expect(result.credentialsCopied).toBe(true)+ await until(() => transport.connectCalls === 2, 'auto-connect attempt')+ const status = manager.status(MachineId('m1'))+ expect(status.state).toBe('disconnected')+ expect(status.lastError).toBe('auth failed')+ })++ it('reports a non-Error install failure in the status', async () => {+ const session = new FakeSession(() => false)+ session.exec = (command, _options) => command.includes('git clone')+ // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- hostile rejection+ // eslint-disable-next-line prefer-promise-reject-errors -- deliberately non-Error: covers install failure normalization+ ? Promise.reject('pnpm blew up')+ : Promise.resolve({ code: 0, stdout: '', stderr: '' })+ const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-install-failed' })+ expect(manager.status(MachineId('m1')).lastError).toBe('pnpm blew up')+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.ts b/packages/dsh-tauri-ssh/src/host/service/manager.tsnew file mode 100644index 00000000..3cd68920--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/manager.ts@@ -0,0 +1,517 @@+import type { Buffer } from 'node:buffer'+import type { Config } from '../storage/index.js'+/**+ * Per-machine connection manager: profile map, the disconnected/connecting/+ * connected state machine, TOFU host-key gating, remote-instance assurance,+ * and the tunnel lifecycle. Transport-agnostic — tests inject a fake+ * transport and never touch the network.+ * @module dsh-tauri-ssh/host/service/manager+ */++import type { MachineId, MachineProfile, MachineView, SshInstallResult, SshLink, SshMachineStatus, SshProgress, SshTestResult } from '../types/index.js'+import type { KnownHostsStore } from './host-keys.js'+import type { SshSession, SshTransport, SshTunnelHandle } from './transport.js'+import { homedir } from 'node:os'+import process from 'node:process'+import { join } from 'pathe'+import { SshError } from '../types/index.js'+import { credentialsCopyCommand, describeExecFailure, DshMissingError, ensureRemoteInstance, firstLineOf, installCommandFor, probeDshCommand, readEnvCredentials } from './bootstrap.js'+import { fingerprintHostKey } from './host-keys.js'++/** One machine's live connection state. */+interface MachineState {+ /** Monotonic attempt counter; a disconnect invalidates in-flight connects. */+ generation: number+ /** Published connection phase; the status source of truth. */+ phase: 'disconnected' | 'connecting' | 'connected'+ /** In-flight connect promise; concurrent connects share it. */+ connecting?: Promise<SshLink>+ /** In-flight install promise; concurrent installs share it. */+ installing?: Promise<SshInstallResult>+ /** The authenticated SSH session, while connected. */+ session?: SshSession+ /** The local tunnel listener, while connected. */+ tunnel?: SshTunnelHandle+ /** The published link, while connected. */+ link?: SshLink+ /** Operator-facing description of the last failed transition. */+ lastError?: string+ /** Whether the last failure was "dsh not installed on the remote". */+ dshMissing?: boolean+ /** Live progress of the in-flight operation. */+ progress?: SshProgress+ /** Ring buffer of the in-flight install's streaming output (newest last). */+ installLog?: string[]+}++/** Manager dependencies (all transport seams injectable for tests). */+export interface SshManagerDeps {+ transport: SshTransport+ knownHosts: KnownHostsStore+ config: Config+ /** Publish one machine's status change (the service emits the seam event). */+ emitStatus: (machineId: MachineId, status: SshMachineStatus) => void+ /** Local dsh `.env` credentials to copy after an install (defaults to the host's own). */+ readEnvCredentials?: () => ReturnType<typeof readEnvCredentials>+}++/** The sentinel rethrown when an in-flight attempt loses to a disconnect. */+class AttemptCancelled extends Error {}++/**+ * The per-machine state machine. All public methods are safe to call+ * concurrently: connects dedupe on the in-flight promise, disconnects settle+ * a live link idempotently, and session-closed callbacks race-check their+ * ownership before tearing down. Every transition publishes through+ * `emitStatus` exactly when it happens; a superseded attempt never publishes.+ */+export class SshManager {+ private readonly profiles = new Map<MachineId, MachineProfile>()+ private readonly states = new Map<MachineId, MachineState>()++ /**+ * @param deps - transport, TOFU store, timing config, and the status publisher.+ */+ constructor(private readonly deps: SshManagerDeps) {}++ /**+ * Replace the profile map (settings changed). Machines whose profile+ * vanished are disconnected; live connections keep their established link+ * until the operator reconnects (a profile edit applies on next connect).+ * @param profiles - the new profile map keyed by machine id.+ */+ refreshProfiles(profiles: ReadonlyMap<MachineId, MachineProfile>): void {+ this.profiles.clear()+ for (const [id, profile] of profiles) this.profiles.set(id, profile)+ for (const id of this.states.keys()) {+ if (!this.profiles.has(id))+ void this.disconnect(id)+ }+ }++ /** Redacted views of every profile, in settings order. */+ profileViews(): MachineView[] {+ return [...this.profiles.values()].map(profileView)+ }++ /** Transport status of every known machine, in settings order. */+ statuses(): SshMachineStatus[] {+ return [...this.profiles.keys()].map(id => this.status(id))+ }++ /** Transport status of one machine; unknown ids report `disconnected`. */+ status(machineId: MachineId): SshMachineStatus {+ const state = this.states.get(machineId)+ const lastError = state?.lastError+ const progress = state?.progress+ return {+ machineId,+ state: state?.phase ?? 'disconnected',+ ...state?.link !== undefined ? { tunnelBaseUrl: state.link.tunnelBaseUrl } : {},+ ...lastError === undefined ? {} : { lastError },+ ...state?.dshMissing === true ? { dshMissing: true } : {},+ ...progress === undefined ? {} : { progress },+ }+ }++ /** The current tunnel link of one machine, when connected. */+ link(machineId: MachineId): SshLink | undefined {+ return this.states.get(machineId)?.link+ }++ /**+ * One-shot probe: authenticate, run `uname -srm`, close. Never starts the+ * remote instance and never leaves a connection behind.+ * @param machineId - the machine to probe.+ * @param signal - aborts the probe.+ * @returns the probe outcome.+ * @throws {SshError} `machine-not-found` for an unknown id.+ */+ async test(machineId: MachineId, signal?: AbortSignal): Promise<SshTestResult> {+ const profile = this.requireProfile(machineId)+ const state = this.ensureState(machineId)+ state.progress = { phase: 'handshake' }+ this.emit(machineId)+ let session: SshSession+ try {+ session = await this.deps.transport.connect(profile, key => this.checkHostKey(machineId, key), signal)+ }+ catch (error) {+ delete state.progress+ this.emit(machineId)+ return { ok: false, message: describeSshFailure(error) }+ }+ delete state.progress+ this.emit(machineId)+ try {+ const result = await session.exec('uname -srm')+ if (result.code !== 0) {+ return { ok: false, message: describeExecFailure(result.code, result.stderr) }+ }+ return { ok: true, banner: result.stdout.trim() }+ }+ catch (error) {+ return { ok: false, message: describeSshFailure(error) }+ }+ finally {+ await session.close()+ }+ }++ /**+ * Establish (or reuse) the machine link: SSH connection, remote-instance+ * assurance, and the local tunnel. Idempotent.+ * @param machineId - the machine to connect.+ * @param signal - aborts the connection attempt.+ * @returns the live link.+ * @throws {SshError} on any failure.+ */+ async connect(machineId: MachineId, signal?: AbortSignal): Promise<SshLink> {+ const profile = this.requireProfile(machineId)+ const state = this.ensureState(machineId)+ if (state.link !== undefined)+ return state.link+ if (state.connecting === undefined) {+ state.phase = 'connecting'+ state.progress = { phase: 'handshake' }+ this.emit(machineId)+ const attempt = this.performConnect(machineId, profile, signal)+ state.connecting = attempt.finally(() => {+ // The slot is only ever replaced while undefined, so the settling+ // attempt always owns it at this point.+ delete this.states.get(machineId)?.connecting+ })+ }+ return state.connecting+ }++ /**+ * Tear down one machine's link, invalidating any in-flight connect.+ * Idempotent for an absent link; unknown ids resolve without writing+ * anything.+ * @param machineId - the machine to disconnect.+ */+ async disconnect(machineId: MachineId): Promise<void> {+ const state = this.states.get(machineId)+ if (state === undefined)+ return+ state.generation += 1+ delete state.lastError+ delete state.dshMissing+ delete state.progress+ delete state.installLog+ const tunnel = state.tunnel+ const session = state.session+ delete state.tunnel+ delete state.session+ delete state.link+ state.phase = 'disconnected'+ if (tunnel !== undefined)+ await tunnel.close().catch(() => undefined)+ if (session !== undefined)+ await session.close().catch(() => undefined)+ this.emit(machineId)+ }++ /**+ * Disconnect every machine (composition teardown).+ */+ async dispose(): Promise<void> {+ await Promise.all([...this.states.keys()].map(id => this.disconnect(id)))+ }++ /** @throws {SshError} `machine-not-found` for an unknown id. */+ private requireProfile(machineId: MachineId): MachineProfile {+ const profile = this.profiles.get(machineId)+ if (profile === undefined) {+ throw new SshError('machine-not-found', machineId, `no SSH machine profile "${machineId}"`)+ }+ return profile+ }++ private ensureState(machineId: MachineId): MachineState {+ let state = this.states.get(machineId)+ if (state === undefined) {+ state = { generation: 0, phase: 'disconnected' }+ this.states.set(machineId, state)+ }+ return state+ }++ /** TOFU gate: accept a known fingerprint, remember a first sight, reject a mismatch. */+ private async checkHostKey(machineId: MachineId, hostKey: Buffer): Promise<boolean> {+ const fingerprint = fingerprintHostKey(hostKey)+ const verdict = await this.deps.knownHosts.verify(machineId, fingerprint)+ if (verdict === 'accepted')+ return true+ if (verdict === 'unknown') {+ await this.deps.knownHosts.accept(machineId, fingerprint)+ return true+ }+ return false+ }++ /**+ * One full connection attempt. Publishes exactly one terminal transition+ * (connected or disconnected) unless a disconnect superseded the attempt —+ * a superseded attempt closes its session and throws without publishing.+ */+ private async performConnect(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshLink> {+ const state = this.ensureState(machineId)+ const generation = state.generation+ let session: SshSession+ try {+ session = await this.deps.transport.connect(profile, key => this.checkHostKey(machineId, key), signal)+ }+ catch (error) {+ if (generation === state.generation) {+ delete state.progress+ state.lastError = describeSshFailure(error)+ state.phase = 'disconnected'+ this.emit(machineId)+ }+ throw new SshError('machine-connect-failed', machineId, describeSshFailure(error))+ }+ try {+ await ensureRemoteInstance(+ session,+ profile,+ this.deps.config.healthCheckTimeoutMs,+ this.deps.config.healthPollIntervalMs,+ this.deps.config.healthPollAttempts,+ (progress) => {+ if (generation === state.generation) {+ state.progress = progress+ this.emit(machineId)+ }+ },+ )+ const tunnel = await session.openTunnel(profile.remotePort)+ // A disconnect that landed anywhere above (bootstrap, tunnel opening)+ // must not publish a link; tear the tunnel down and abort the attempt.+ if (generation !== state.generation) {+ await tunnel.close().catch(() => undefined)+ throw new AttemptCancelled()+ }+ const link: SshLink = {+ machineId,+ tunnelBaseUrl: `http://127.0.0.1:${tunnel.localPort}`,+ }+ state.session = session+ state.tunnel = tunnel+ state.link = link+ delete state.progress+ state.phase = 'connected'+ session.onClosed(() => {+ const current = this.states.get(machineId)+ if (current?.session !== session)+ return+ current.lastError = 'SSH connection closed'+ const tunnel = current.tunnel+ delete current.session+ delete current.tunnel+ delete current.link+ current.phase = 'disconnected'+ void tunnel?.close().catch(() => undefined)+ this.emit(machineId)+ })+ this.emit(machineId)+ return link+ }+ catch (error) {+ await session.close().catch(() => undefined)+ if (error instanceof AttemptCancelled) {+ throw new SshError('machine-connect-failed', machineId, 'connection cancelled by disconnect')+ }+ if (generation === state.generation) {+ delete state.progress+ state.lastError = error instanceof Error ? error.message : String(error)+ if (error instanceof DshMissingError)+ state.dshMissing = true+ state.phase = 'disconnected'+ this.emit(machineId)+ }+ throw new SshError(+ error instanceof DshMissingError ? 'machine-dsh-missing' : 'machine-bootstrap-failed',+ machineId,+ state.lastError ?? 'remote instance bootstrap failed',+ )+ }+ }++ /**+ * One-shot remote dsh install: authenticate, stream the official installer+ * (clone + pnpm install + build), resolve the installed binary, copy the+ * local API credentials into the remote `~/.dsh/.env`, then hand off to+ * {@link connect} automatically. Idempotent while in flight.+ * @param machineId - the machine to install on.+ * @param signal - aborts the attempt.+ * @returns the install outcome.+ * @throws {SshError} on any failure (connect, install, or probe).+ */+ async install(machineId: MachineId, signal?: AbortSignal): Promise<SshInstallResult> {+ const profile = this.requireProfile(machineId)+ const state = this.ensureState(machineId)+ if (state.installing === undefined) {+ state.progress = { phase: 'installing' }+ this.emit(machineId)+ const attempt = this.performInstall(machineId, profile, signal)+ state.installing = attempt.finally(() => {+ // The slot is only ever replaced while undefined, so the settling+ // attempt always owns it at this point.+ delete this.states.get(machineId)?.installing+ })+ }+ return state.installing+ }++ /**+ * One full install attempt. Publishes the terminal transition unless a+ * disconnect superseded the attempt; a successful install hands off to+ * {@link connect} (fire-and-forget — its outcome lands in the status).+ */+ private async performInstall(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshInstallResult> {+ const state = this.ensureState(machineId)+ const generation = state.generation+ let session: SshSession+ try {+ session = await this.deps.transport.connect(profile, key => this.checkHostKey(machineId, key), signal)+ }+ catch (error) {+ if (generation === state.generation) {+ delete state.progress+ state.lastError = describeSshFailure(error)+ state.phase = 'disconnected'+ this.emit(machineId)+ }+ throw new SshError('machine-connect-failed', machineId, describeSshFailure(error))+ }+ try {+ const installTimeoutMs = this.deps.config.installTimeoutMs+ const result = await session.exec(installCommandFor(this.deps.config), {+ ...installTimeoutMs === undefined ? {} : { timeoutMs: installTimeoutMs },+ onData: (chunk) => {+ if (generation !== state.generation)+ return+ state.installLog = [...(state.installLog ?? []), chunk].slice(-40)+ state.progress = {+ phase: 'installing',+ log: state.installLog.join('').slice(-2000),+ }+ },+ })+ if (result.code !== 0) {+ const log = state.installLog?.join('').trim() ?? ''+ const tail = log === '' ? '(no output captured)' : log.split('\n').slice(-5).join(' | ')+ throw new Error(+ `dsh install failed on "${profile.host}": ${describeExecFailure(result.code, result.stderr)}; `+ + `installer output tail: ${tail}`,+ )+ }+ if (generation !== state.generation)+ throw new AttemptCancelled()+ const dshPath = firstLineOf((await session.exec(probeDshCommand())).stdout)+ if (dshPath === '') {+ throw new Error(+ `dsh install finished on "${profile.host}" but no dsh binary is reachable `+ + '(checked the login PATH, ~/.local/bin and ~/.dsh/source/current)',+ )+ }+ let credentialsCopied = false+ let credentialsError: string | undefined+ try {+ credentialsCopied = await this.copyCredentials(session)+ }+ catch (error) {+ credentialsError = error instanceof Error ? error.message : String(error)+ }+ await session.close().catch(() => undefined)+ if (generation === state.generation) {+ delete state.progress+ delete state.dshMissing+ delete state.installLog+ delete state.lastError+ state.phase = 'disconnected'+ this.emit(machineId)+ // The operator's intent behind "install" is "connect": hand off and+ // let the connect plane report its own progress/outcome.+ void this.connect(machineId).catch(() => undefined)+ }+ return {+ dshPath,+ credentialsCopied,+ ...credentialsError === undefined ? {} : { credentialsError },+ }+ }+ catch (error) {+ await session.close().catch(() => undefined)+ if (error instanceof AttemptCancelled) {+ throw new SshError('machine-install-failed', machineId, 'install cancelled by disconnect')+ }+ if (generation === state.generation) {+ delete state.progress+ delete state.installLog+ state.lastError = error instanceof Error ? error.message : String(error)+ state.phase = 'disconnected'+ this.emit(machineId)+ }+ throw new SshError('machine-install-failed', machineId, state.lastError ?? 'dsh install failed')+ }+ }++ /**+ * Copy the local API credentials into the remote `~/.dsh/.env`, unless the+ * remote already carries a key (kept untouched). A failure to read the+ * local `.env` is not an error — it just reports `false`.+ * @param session - the authenticated session (install connection).+ * @returns whether the credentials were copied.+ */+ private async copyCredentials(session: SshSession): Promise<boolean> {+ const credentials = (this.deps.readEnvCredentials ?? defaultEnvCredentials)()+ const apiKey = credentials.apiKey+ if (apiKey === undefined)+ return false+ const result = await session.exec(credentialsCopyCommand({+ apiKey,+ ...credentials.baseUrl === undefined ? {} : { baseUrl: credentials.baseUrl },+ }))+ if (result.code !== 0) {+ throw new Error(`writing remote credentials failed: ${describeExecFailure(result.code, result.stderr)}`)+ }+ return result.stdout.includes('copied')+ }++ private emit(machineId: MachineId): void {+ this.deps.emitStatus(machineId, this.status(machineId))+ }+}++/** Redacted wire view of one profile. */+export function profileView(profile: MachineProfile): MachineView {+ return {+ id: profile.id,+ name: profile.name,+ host: profile.host,+ port: profile.port,+ user: profile.user,+ hasPassword: profile.password !== undefined,+ hasPassphrase: profile.passphrase !== undefined,+ remotePort: profile.remotePort,+ ...profile.startCommand === undefined ? {} : { startCommand: profile.startCommand },+ ...profile.color === undefined ? {} : { color: profile.color },+ ...profile.tintBorder === true ? { tintBorder: true } : {},+ }+}++/** One operator-facing fragment for an SSH transport failure. */+export function describeSshFailure(error: unknown): string {+ const message = error instanceof Error ? error.message : String(error)+ if (message === '')+ return 'SSH connection failed'+ return message+}++/** The default local `.env` read: the harness home (`$DSH_HOME`, else `~/.dsh`). */+function defaultEnvCredentials(): ReturnType<typeof readEnvCredentials> {+ return readEnvCredentials(join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), '.env'))+}diff --git a/packages/dsh-tauri-ssh/src/host/service/ssh-config.test.ts b/packages/dsh-tauri-ssh/src/host/service/ssh-config.test.tsnew file mode 100644index 00000000..b4dbcc9e--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/ssh-config.test.ts@@ -0,0 +1,365 @@+/**+ * The `~/.ssh` credential layer: config parsing, OpenSSH matching semantics,+ * Include expansion, and the resolver. All file access is sandboxed into a+ * scratch ssh directory per test — the developer's real `~/.ssh` is never+ * read.+ */++import type { MachineProfile } from '../types/index.js'+import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'pathe'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { MachineId } from '../types/index.js'+import {+ DEFAULT_IDENTITY_FILES,+ discoverableHosts,+ expandIncludePath,+ expandTokenPath,+ hostPatternMatches,+ loadSshConfigBlocks,+ lookupSshConfig,+ parseSshConfig,+ SshConfigResolver,+} from './ssh-config.js'++const FIXTURES = join(import.meta.dirname, 'fixtures')++let home: string+let sshDir: string++beforeEach(async () => {+ home = await mkdtemp(join(tmpdir(), 'ssh-home-'))+ sshDir = join(home, '.ssh')+ await mkdir(sshDir, { recursive: true })+})++afterEach(async () => {+ await rm(home, { recursive: true, force: true })+})++/** A machine profile that resolves against the scratch ssh dir. */+function profile(overrides: Partial<MachineProfile> = {}): MachineProfile {+ return {+ id: MachineId('m1'),+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ remotePort: 3080,+ ...overrides,+ }+}++/** Copy every fixture identity file into the scratch ssh dir. */+async function installFixtures(): Promise<void> {+ await copyFile(join(FIXTURES, 'id_ed25519'), join(sshDir, 'id_ed25519'))+ await copyFile(join(FIXTURES, 'id_ed25519.pub'), join(sshDir, 'id_ed25519.pub'))+ await copyFile(join(FIXTURES, 'id_ed25519_enc'), join(sshDir, 'id_ed25519_enc'))+ await copyFile(join(FIXTURES, 'garbage.txt'), join(sshDir, 'garbage.txt'))+}++describe('parseSshConfig', () => {+ it('parses Host blocks, case-insensitive keywords, and both separators', () => {+ const blocks = parseSshConfig([+ 'Host webserver',+ ' HostName 10.0.0.9',+ ' User = deploy',+ ' PORT 2222',+ '',+ 'Host *',+ '\tIdentityFile ~/.ssh/one',+ '# a comment',+ ' IdentityFile=~/.ssh/two',+ ].join('\n'))+ expect(blocks).toEqual([+ { patterns: ['webserver'], values: { hostname: ['10.0.0.9'], user: ['deploy'], port: ['2222'] } },+ { patterns: ['*'], values: { identityfile: ['~/.ssh/one', '~/.ssh/two'] } },+ ])+ })++ it('drops lines before the first Host block and skips Match', () => {+ const blocks = parseSshConfig([+ 'User nobody',+ 'Match host foo',+ ' User someone-else',+ 'Host box',+ ].join('\n'))+ expect(blocks).toEqual([{ patterns: ['box'], values: {} }])+ })++ it('keeps multi-word Host pattern lists', () => {+ const blocks = parseSshConfig('Host a b c\n User u\n')+ expect(blocks[0]?.patterns).toEqual(['a', 'b', 'c'])+ })++ it('skips empty keys and values', () => {+ const blocks = parseSshConfig(['= x', 'Host', ' User', 'Host box', ' User u'].join('\n'))+ expect(blocks).toEqual([{ patterns: ['box'], values: { user: ['u'] } }])+ })+})++describe('hostPatternMatches', () => {+ it('matches literals, case-insensitively', () => {+ expect(hostPatternMatches('WebServer', 'webserver')).toBe(true)+ expect(hostPatternMatches('webserver', 'other')).toBe(false)+ })++ it('matches * and ? globs', () => {+ expect(hostPatternMatches('*.example.com', 'box.example.com')).toBe(true)+ expect(hostPatternMatches('*.example.com', 'box.example.org')).toBe(false)+ expect(hostPatternMatches('box?', 'box1')).toBe(true)+ expect(hostPatternMatches('box?', 'box')).toBe(false)+ })++ it('decides on the first matching comma alternative, negation included', () => {+ expect(hostPatternMatches('!foo,bar', 'foo')).toBe(false)+ expect(hostPatternMatches('!foo,bar', 'bar')).toBe(true)+ expect(hostPatternMatches('!foo,bar', 'baz')).toBe(false)+ })++ it('backtracks a greedy star', () => {+ expect(hostPatternMatches('a*c', 'abc')).toBe(true)+ expect(hostPatternMatches('a*b*c', 'aXXbYYc')).toBe(true)+ expect(hostPatternMatches('a*c', 'abxd')).toBe(false)+ })+})++describe('discoverableHosts', () => {+ it('keeps literal aliases, drops wildcards, negations, and comma alternations', () => {+ const blocks = parseSshConfig([+ 'Host dev ci',+ 'Host github.com',+ 'Host *.example.com',+ 'Host !banned',+ 'Host a,b',+ 'Host *',+ ].join('\n'))+ expect(discoverableHosts(blocks)).toEqual(['ci', 'dev', 'github.com'])+ })++ it('deduplicates aliases across blocks and sorts them', () => {+ const blocks = parseSshConfig('Host b\nHost a\nHost b\n')+ expect(discoverableHosts(blocks)).toEqual(['a', 'b'])+ })++ it('lists nothing for no blocks or no literal patterns', () => {+ expect(discoverableHosts([])).toEqual([])+ expect(discoverableHosts(parseSshConfig('Host *\nHost !x\n'))).toEqual([])+ })+})++describe('expandTokenPath', () => {+ it('expands ~, ~/, bare relative paths, and the %d/%h/%r tokens', () => {+ expect(expandTokenPath('~', home, 'h', 'r')).toBe(home)+ expect(expandTokenPath('~/keys/id', home, 'h', 'r')).toBe(join(home, 'keys/id'))+ expect(expandTokenPath('keys/id', home, 'h', 'r')).toBe(join(home, 'keys/id'))+ expect(expandTokenPath('/abs/path', home, 'h', 'r')).toBe('/abs/path')+ expect(expandTokenPath('%d/id_%h_%r', home, 'box', 'ops')).toBe(join(home, `id_box_ops`))+ })+})++describe('expandIncludePath', () => {+ it('keeps literal paths and anchors bare relative ones under the ssh dir', () => {+ expect(expandIncludePath('~/.ssh/extra', sshDir, home, '', '')).toEqual([join(home, '.ssh/extra')])+ expect(expandIncludePath('/etc/ssh/extra', sshDir, home, '', '')).toEqual(['/etc/ssh/extra'])+ expect(expandIncludePath('conf.d/a', sshDir, home, '', '')).toEqual([join(sshDir, 'conf.d/a')])+ })++ it('expands a basename glob into sorted matches, dropping nothing existing', async () => {+ await mkdir(join(sshDir, 'conf.d'), { recursive: true })+ await writeFile(join(sshDir, 'conf.d/b.conf'), 'Host b\n')+ await writeFile(join(sshDir, 'conf.d/a.conf'), 'Host a\n')+ await writeFile(join(sshDir, 'conf.d/other.txt'), '')+ expect(expandIncludePath('conf.d/*.conf', sshDir, home, '', '')).toEqual([+ join(sshDir, 'conf.d/a.conf'),+ join(sshDir, 'conf.d/b.conf'),+ ])+ })++ it('reads an unreadable directory as no targets', () => {+ expect(expandIncludePath('missing/*.conf', sshDir, home, '', '')).toEqual([])+ })++ it('anchors separator-less paths under the ssh dir, glob or literal', async () => {+ await writeFile(join(sshDir, 'root.conf'), 'Host r\n')+ expect(expandIncludePath('plain', sshDir, home, '', '')).toEqual([join(sshDir, 'plain')])+ expect(expandIncludePath('*.conf', sshDir, home, '', '')).toEqual([join(sshDir, 'root.conf')])+ })+})++describe('lookupSshConfig', () => {+ it('applies first-match-wins per parameter and accumulates IdentityFile across matching blocks', () => {+ const blocks = parseSshConfig([+ 'Host 10.0.0.1',+ ' HostName 10.0.0.1',+ ' User first',+ ' IdentityFile ~/.ssh/one',+ 'Host 10.0.0.*',+ ' User second',+ ' Port 2222',+ ' IdentityFile ~/.ssh/two',+ ].join('\n'))+ const settings = lookupSshConfig(blocks, '10.0.0.1')+ expect(settings).toEqual({+ hostName: '10.0.0.1',+ user: 'first',+ port: 2222,+ identityFiles: ['~/.ssh/one', '~/.ssh/two'],+ })+ })++ it('skips negated blocks and non-matching wildcards', () => {+ const blocks = parseSshConfig([+ 'Host !10.0.0.1 *.example.com',+ ' User special',+ ' IdentityFile ~/.ssh/special',+ 'Host *',+ ' IdentityFile ~/.ssh/generic',+ ].join('\n'))+ const settings = lookupSshConfig(blocks, 'box.example.com')+ expect(settings.user).toBe('special')+ expect(settings.identityFiles).toEqual(['~/.ssh/special', '~/.ssh/generic'])+ const excluded = lookupSshConfig(blocks, '10.0.0.1')+ expect(excluded.user).toBeUndefined()+ expect(excluded.identityFiles).toEqual(['~/.ssh/generic'])+ })++ it('returns only the defaults shape for no matches', () => {+ expect(lookupSshConfig([], 'anything')).toEqual({ identityFiles: [] })+ })+})++describe('loadSshConfigBlocks', () => {+ it('reads nothing for a missing config', async () => {+ expect(await loadSshConfigBlocks(sshDir, home)).toEqual([])+ })++ it('loads the main config and recursive includes with relative and glob paths', async () => {+ await mkdir(join(sshDir, 'conf.d'), { recursive: true })+ await writeFile(join(sshDir, 'conf.d/base.conf'), 'Host base\n User b\n')+ await writeFile(join(sshDir, 'conf.d/extra.conf'), 'Include conf.d/base.conf\nHost extra\n User e\n')+ await writeFile(join(sshDir, 'config'), [+ 'Host main\n User m\n',+ 'Include conf.d/*.conf\n',+ 'Host after\n User a\n',+ ].join(''))+ const blocks = await loadSshConfigBlocks(sshDir, home)+ const names = blocks.map(block => block.patterns[0])+ expect(names).toEqual(['main', 'base', 'extra', 'after'])+ expect(blocks[1]?.values.user).toEqual(['b'])+ })++ it('skips missing includes silently and caps the include depth', async () => {+ await mkdir(join(sshDir, 'chain'), { recursive: true })+ for (let i = 0; i < 12; i++) {+ const next = i + 1+ await writeFile(join(sshDir, 'chain', `c${i}.conf`), `Include chain/c${next}.conf\nHost c${i}\n`)+ }+ await writeFile(join(sshDir, 'chain', 'c12.conf'), 'Host c12\n')+ await writeFile(join(sshDir, 'config'), 'Include chain/c0.conf\nInclude /missing/nowhere\n')+ const blocks = await loadSshConfigBlocks(sshDir, home)+ expect(blocks.length).toBeLessThan(12)+ })++ it('never revisits the same file (cycle safety)', async () => {+ await mkdir(join(sshDir, 'loop'), { recursive: true })+ await writeFile(join(sshDir, 'loop/a.conf'), 'Include loop/b.conf\nHost a\n')+ await writeFile(join(sshDir, 'loop/b.conf'), 'Include loop/a.conf\nHost b\n')+ await writeFile(join(sshDir, 'config'), 'Include loop/a.conf\n')+ const blocks = await loadSshConfigBlocks(sshDir, home)+ expect(blocks.map(block => block.patterns[0])).toEqual(['b', 'a'])+ })+})++describe('sshConfigResolver', () => {+ it('uses the profile fields and default identity files when no config exists', async () => {+ await installFixtures()+ const resolver = new SshConfigResolver(sshDir, home, 'fallback-user')+ const auth = await resolver.resolve(profile())+ expect(auth).toMatchObject({ host: '10.0.0.1', port: 22, username: 'root' })+ // Defaults are id_ed25519/id_ecdsa/id_rsa; the missing ones are skipped.+ expect(auth.keys).toEqual([{ privateKey: await readFile(join(sshDir, 'id_ed25519'), 'utf8') }])+ expect(DEFAULT_IDENTITY_FILES).toEqual(['id_ed25519', 'id_ecdsa', 'id_rsa'])+ })++ it('resolves a config alias: HostName/User/Port/IdentityFile override the profile', async () => {+ await installFixtures()+ await writeFile(join(sshDir, 'config'), [+ 'Host webserver',+ ' HostName 10.0.0.9',+ ' User deploy',+ ' Port 2222',+ ' IdentityFile %d/.ssh/id_ed25519',+ ].join('\n'))+ const resolver = new SshConfigResolver(sshDir, home, 'fallback')+ const auth = await resolver.resolve(profile({ host: 'webserver', user: '' }))+ expect(auth).toMatchObject({ host: '10.0.0.9', port: 2222, username: 'deploy' })+ expect(auth.keys).toEqual([{ privateKey: await readFile(join(sshDir, 'id_ed25519'), 'utf8') }])+ })++ it('hands every configured IdentityFile to ssh2 as-is (it validates and skips)', async () => {+ await installFixtures()+ await writeFile(join(sshDir, 'config'), [+ 'Host box',+ ' IdentityFile .ssh/id_ed25519.pub',+ ' IdentityFile .ssh/id_ed25519_enc',+ ' IdentityFile .ssh/garbage.txt',+ ' IdentityFile %h-keys/id',+ ].join('\n'))+ const resolver = new SshConfigResolver(sshDir, home, 'os-user')+ const auth = await resolver.resolve(profile({ host: 'box', user: '' }))+ expect(auth.keys).toEqual([+ { privateKey: await readFile(join(sshDir, 'id_ed25519.pub'), 'utf8') },+ { privateKey: await readFile(join(sshDir, 'id_ed25519_enc'), 'utf8') },+ { privateKey: await readFile(join(sshDir, 'garbage.txt'), 'utf8') },+ ])+ })++ it('prefers the profile user over the config user over the default user', async () => {+ await writeFile(join(sshDir, 'config'), 'Host box\n User config-user\n')+ const resolver = new SshConfigResolver(sshDir, home, 'os-user')+ expect((await resolver.resolve(profile({ host: 'box', user: 'profile-user' }))).username).toBe('profile-user')+ expect((await resolver.resolve(profile({ host: 'box', user: '' }))).username).toBe('config-user')+ expect((await resolver.resolve(profile({ host: 'no-match', user: '' }))).username).toBe('os-user')+ })++ it('attaches the stored password and passphrase, and skips unreadable keys', async () => {+ await installFixtures()+ await writeFile(join(sshDir, 'config'), 'Host box\n IdentityFile %h-keys/id\n IdentityFile .ssh/id_ed25519\n')+ const resolver = new SshConfigResolver(sshDir, home, 'os-user')+ const auth = await resolver.resolve(profile({+ host: 'box',+ user: '',+ password: 'pw',+ passphrase: 'phrase',+ }))+ expect(auth.password).toBe('pw')+ expect(auth.keys).toEqual([{ privateKey: await readFile(join(sshDir, 'id_ed25519'), 'utf8'), passphrase: 'phrase' }])+ })++ it('re-reads keys on every resolve (fresh ~/.ssh)', async () => {+ await installFixtures()+ const resolver = new SshConfigResolver(sshDir, home)+ const first = await resolver.resolve(profile())+ const rotated = '-----BEGIN OPENSSH PRIVATE KEY-----\nrotated\n'+ await writeFile(join(sshDir, 'id_ed25519'), rotated)+ const second = await resolver.resolve(profile())+ expect(first.keys[0]?.privateKey).not.toBe(rotated)+ expect(second.keys[0]?.privateKey).toBe(rotated)+ })++ it('falls back to an empty user when nothing names one', async () => {+ const previous = process.env.USER+ try {+ delete process.env.USER+ const resolver = new SshConfigResolver(sshDir, home)+ const auth = await resolver.resolve(profile({ user: '' }))+ expect(auth.username).toBe('')+ }+ finally {+ if (previous !== undefined)+ process.env.USER = previous+ }+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/ssh-config.ts b/packages/dsh-tauri-ssh/src/host/service/ssh-config.tsnew file mode 100644index 00000000..4f59d060--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/ssh-config.ts@@ -0,0 +1,374 @@+import type { MachineProfile } from '../types/index.js'+/**+ * The host's own `~/.ssh` as the credential source: `ssh_config` parsing+ * (Host blocks, HostName/User/Port/IdentityFile, Include expansion), the+ * OpenSSH matching semantics (first matching pattern decides; first obtained+ * value per parameter; IdentityFile accumulates), and the resolver that turns+ * one machine profile into a concrete connection plan (connect host/port/user+ * plus the ordered identity files to try). Keys are read fresh on every+ * connect — a key added to `~/.ssh` is picked up without touching DSH.+ *+ * Deliberate subset: `Match` blocks, `ProxyJump`, and agent forwarding are+ * out of scope; a host with no config match falls back to the profile fields+ * and the default identity files, exactly like a bare `ssh host` would.+ * @module dsh-tauri-ssh/host/service/ssh-config+ */++import { readdirSync } from 'node:fs'+import { readFile } from 'node:fs/promises'+import process from 'node:process'+import { join, sep } from 'pathe'++/** Default identity file basenames, tried in order when no config `IdentityFile` exists. */+export const DEFAULT_IDENTITY_FILES = ['id_ed25519', 'id_ecdsa', 'id_rsa']++/** The config file name inside the ssh directory. */+export const SSH_CONFIG_FILE = 'config'++/** Recursion cap for `Include` chains; OpenSSH effectively has none, this one is for safety. */+export const INCLUDE_DEPTH_LIMIT = 8++/** One `Host` block: the patterns it applies to and the settings it carries. */+export interface SshHostBlock {+ /** The `Host` pattern list of this block (may contain `!`, `*`, `?`). */+ patterns: string[]+ /** Settings keyed by lower-cased keyword; every keyword may appear multiple times. */+ values: Record<string, string[]>+}++/** The resolved per-host settings for one connection. */+export interface SshHostSettings {+ /** `HostName` override; absent means "connect to the requested host directly". */+ hostName?: string+ /** `User` override. */+ user?: string+ /** `Port` override (parsed). */+ port?: number+ /** Every `IdentityFile` from the matching blocks, in order. */+ identityFiles: string[]+}++/** The concrete connection plan one machine profile resolves to. */+export interface ResolvedSshAuth {+ /** The host to actually connect to. */+ host: string+ /** The TCP port to actually connect to. */+ port: number+ /** The login user name. */+ username: string+ /** The stored password fallback, when the profile carries one. */+ password?: string+ /** The identity files to try, in order, as raw file contents. */+ keys: Array<{ privateKey: string, passphrase?: string }>+}++/** Token expansion for `~`, `%d`, `%h`, `%r` in config paths (the OpenSSH subset). */+export function expandTokenPath(path: string, homeDir: string, host: string, user: string): string {+ let out = expandPathTokens(path, homeDir, host, user)+ if (!out.startsWith('/')) {+ // ssh_config resolves bare relative IdentityFile paths under the home dir.+ out = join(homeDir, out)+ }+ return out+}++/** Expand `~`, `~/"`, `%d`, `%h`, `%r` without anchoring a bare relative path. */+function expandPathTokens(path: string, homeDir: string, host: string, user: string): string {+ let out = path+ if (out === '~') {+ out = homeDir+ }+ else if (out.startsWith('~/')) {+ out = join(homeDir, out.slice(2))+ }+ return out.replaceAll('%d', homeDir).replaceAll('%h', host).replaceAll('%r', user)+}++/**+ * Whether one `Host` pattern matches a host name. `*` matches any run of+ * characters, `?` exactly one; the pattern may be comma-separated, each+ * alternative tried in order — the first one that matches decides, and a+ * leading `!` (negation) turns that decision into "no match". Case-insensitive,+ * like OpenSSH host names.+ */+export function hostPatternMatches(pattern: string, host: string): boolean {+ const lowered = host.toLowerCase()+ for (const alternative of pattern.split(',')) {+ const negated = alternative.startsWith('!')+ const body = negated ? alternative.slice(1) : alternative+ if (globMatches(body.toLowerCase(), lowered))+ return !negated+ }+ return false+}++/** Match one glob (only `*` and `?`) against a string. */+export function globMatches(glob: string, value: string): boolean {+ // A greedy two-pointer matcher: walk both strings, backtrack on `*`.+ let globIndex = 0+ let valueIndex = 0+ let starGlob = -1+ let starValue = -1+ while (valueIndex < value.length) {+ const g = glob[globIndex]+ if (g === '*') {+ starGlob = globIndex+ starValue = valueIndex+ globIndex += 1+ }+ else if (g === '?' || g === value[valueIndex]) {+ globIndex += 1+ valueIndex += 1+ }+ else if (starGlob !== -1) {+ globIndex = starGlob + 1+ starValue += 1+ valueIndex = starValue+ }+ else {+ return false+ }+ }+ while (glob[globIndex] === '*') globIndex += 1+ return globIndex === glob.length+}++/**+ * Parse one ssh_config document into `Host` blocks. Keywords are+ * case-insensitive; `#` starts a comment; `key value` and `key=value` both+ * parse. Only `Host` opens a block; a top-level `Include` (before any `Host`)+ * becomes a synthetic pattern-less block the loader expands in place. Other+ * lines outside any block are dropped (OpenSSH applies them to every host,+ * but the common `Host *` form parses the same way).+ */+export function parseSshConfig(text: string): SshHostBlock[] {+ const blocks: SshHostBlock[] = []+ let current: SshHostBlock | undefined+ for (const rawLine of text.split('\n')) {+ const line = rawLine.replace(/#.*$/u, '').trim()+ if (line === '')+ continue+ const equals = line.indexOf('=')+ // The line is non-blank, so the split always yields a first token.+ const key = (equals === -1 ? line.split(/\s+/u)[0]! : line.slice(0, equals)).trim().toLowerCase()+ if (key === '')+ continue+ const value = equals === -1+ ? line.slice(key.length).trim()+ : line.slice(equals + 1).trim()+ if (value === '')+ continue+ if (key === 'host') {+ current = {+ patterns: value.split(/\s+/u).filter(part => part !== ''),+ values: {},+ }+ blocks.push(current)+ continue+ }+ if (current === undefined) {+ if (key === 'include') {+ current = { patterns: [], values: {} }+ blocks.push(current)+ }+ else {+ continue+ }+ }+ const values = current.values[key] ?? (current.values[key] = [])+ values.push(value)+ }+ return blocks+}++/**+ * Resolve one host name against parsed blocks, with the OpenSSH rules: a+ * block applies when its first matching pattern decides (a matching negation+ * excludes the block), the first obtained value per parameter wins, and+ * `IdentityFile` accumulates across all matching blocks.+ */+export function lookupSshConfig(blocks: SshHostBlock[], host: string): SshHostSettings {+ const settings: SshHostSettings = { identityFiles: [] }+ for (const block of blocks) {+ const applies = block.patterns.some(pattern => hostPatternMatches(pattern, host))+ if (!applies)+ continue+ const hostname = block.values.hostname?.[0]+ if (settings.hostName === undefined && hostname !== undefined) {+ settings.hostName = hostname+ }+ const user = block.values.user?.[0]+ if (settings.user === undefined && user !== undefined) {+ settings.user = user+ }+ const port = block.values.port?.[0]+ if (settings.port === undefined && port !== undefined) {+ settings.port = Number(port)+ }+ if (block.values.identityfile !== undefined) {+ settings.identityFiles.push(...block.values.identityfile)+ }+ }+ return settings+}++/**+ * The literal `Host` aliases worth surfacing as machines: every pattern token+ * that names one concrete host — no `*`/`?` wildcards, no `!` negation, no+ * comma alternation. Multi-pattern entries contribute each literal token;+ * the result is deduplicated and sorted.+ */+export function discoverableHosts(blocks: SshHostBlock[]): string[] {+ const hosts = new Set<string>()+ for (const block of blocks) {+ for (const pattern of block.patterns) {+ if (pattern === '' || /[?*,!]/u.test(pattern))+ continue+ hosts.add(pattern)+ }+ }+ return [...hosts].sort()+}++/**+ * Expand one `Include` path into the file paths it names (sorted, missing+ * targets dropped). OpenSSH anchors relative paths under the ssh directory+ * (the user config home) and globs the basename.+ */+export function expandIncludePath(path: string, sshDir: string, homeDir: string, host: string, user: string): string[] {+ let expanded = expandPathTokens(path, homeDir, host, user)+ if (!expanded.startsWith('/'))+ expanded = join(sshDir, expanded)+ // The path is absolute by now, so a separator always exists.+ const slash = expanded.lastIndexOf(sep)+ const dir = expanded.slice(0, slash)+ const basename = expanded.slice(slash + 1)+ if (!/[?*]/u.test(basename))+ return [expanded]+ // Basename globs only (the common `Include ~/.ssh/config.d/*` shape);+ // readdirSyncSafe never throws, an unreadable directory reads as empty.+ return readdirSyncSafe(dir)+ .filter(name => globMatches(basename, name))+ .sort()+ .map(name => join(dir, name))+}++/** One synchronous directory listing; failures read as an empty list. */+function readdirSyncSafe(dir: string): string[] {+ try {+ return readdirSync(dir)+ }+ catch {+ return []+ }+}++/**+ * Load every `Host` block reachable from the ssh config, following `Include`+ * chains (depth-capped, cycle-safe, missing targets silently skipped).+ * @param sshDir - the ssh directory (defaults to `~/.ssh`).+ * @param homeDir - the home directory for `~` expansion.+ * @returns the concatenated blocks, outermost first.+ */+export async function loadSshConfigBlocks(sshDir: string, homeDir: string): Promise<SshHostBlock[]> {+ const blocks: SshHostBlock[] = []+ const visited = new Set<string>()+ await collectConfigBlocks(sshDir, homeDir, join(sshDir, SSH_CONFIG_FILE), 0, visited, blocks)+ return blocks+}++/** One recursive leg of {@link loadSshConfigBlocks}. */+async function collectConfigBlocks(+ sshDir: string,+ homeDir: string,+ file: string,+ depth: number,+ visited: Set<string>,+ out: SshHostBlock[],+): Promise<void> {+ if (depth > INCLUDE_DEPTH_LIMIT || visited.has(file))+ return+ visited.add(file)+ let text: string+ try {+ text = await readFile(file, 'utf8')+ }+ catch {+ return+ }+ for (const block of parseSshConfig(text)) {+ const includes = block.values.include+ if (includes === undefined) {+ out.push(block)+ continue+ }+ // OpenSSH splices include content in place: a Host block that carries an+ // Include keeps its own settings (the Include keyword is not itself a+ // setting), and the included files' blocks follow it. A synthetic+ // pattern-less block (top-level Include) contributes only its includes.+ if (block.patterns.length > 0) {+ const { include: _dropped, ...values } = block.values+ out.push({ patterns: block.patterns, values })+ }+ for (const path of includes) {+ for (const target of expandIncludePath(path, sshDir, homeDir, '', '')) {+ await collectConfigBlocks(sshDir, homeDir, target, depth + 1, visited, out)+ }+ }+ }+}++/**+ * The credential resolver: reads the host's `~/.ssh` and turns one machine+ * profile into the concrete connection plan. Pure file access — no network,+ * no ssh2 — so tests drive it with a scratch ssh directory.+ */+export class SshConfigResolver {+ /**+ * @param sshDir - the ssh directory holding `config` and the identity files.+ * @param homeDir - the home directory used for `~` expansion.+ * @param defaultUser - the OS user name used when neither the profile nor+ * the config names a user (what a bare `ssh` would log in as).+ */+ constructor(+ private readonly sshDir: string,+ private readonly homeDir: string,+ private readonly defaultUser: string = process.env.USER ?? '',+ ) {}++ /**+ * Resolve one machine profile into the connection plan.+ * @param profile - the machine profile to connect.+ * @returns the host/port/user to connect and the ordered credentials.+ */+ async resolve(profile: MachineProfile): Promise<ResolvedSshAuth> {+ const blocks = await loadSshConfigBlocks(this.sshDir, this.homeDir)+ const settings = lookupSshConfig(blocks, profile.host)+ const username = profile.user !== '' ? profile.user : settings.user ?? this.defaultUser+ const host = settings.hostName ?? profile.host+ const port = settings.port ?? profile.port+ const passphrase = profile.passphrase === undefined || profile.passphrase === '' ? undefined : profile.passphrase+ const password = profile.password === undefined || profile.password === '' ? undefined : profile.password+ const identityPaths = settings.identityFiles.length > 0+ ? settings.identityFiles+ : DEFAULT_IDENTITY_FILES.map(name => join(this.sshDir, name))+ const keys: ResolvedSshAuth['keys'] = []+ for (const path of identityPaths) {+ const expanded = expandTokenPath(path, this.homeDir, host, username)+ try {+ const privateKey = await readFile(expanded, 'utf8')+ keys.push({ privateKey, ...passphrase === undefined ? {} : { passphrase } })+ }+ catch {+ // Missing or unreadable identity files are skipped, like ssh does.+ }+ }+ return {+ host,+ port,+ username,+ keys,+ ...password === undefined ? {} : { password },+ }+ }+}diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.test.ts b/packages/dsh-tauri-ssh/src/host/service/transport.test.tsnew file mode 100644index 00000000..48e9b849--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/transport.test.ts@@ -0,0 +1,486 @@+import type { MachineProfile } from '../types/index.js'+import { Buffer } from 'node:buffer'+import { EventEmitter } from 'node:events'+import { Server, connect as tcpConnect } from 'node:net'+import { PassThrough } from 'node:stream'+import { describe, expect, it, vi } from 'vitest'+import { MachineId } from '../types/index.js'+import { loginShell, shQuote, Ssh2Transport } from './transport.js'++const profile: MachineProfile = {+ id: MachineId('m1'),+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ password: 'sekrit',+ remotePort: 3080,+}++/** The profile minus its stored password (exactOptionalPropertyTypes-safe). */+function withoutPassword(profile: MachineProfile): MachineProfile {+ const { password: _password, ...rest } = profile+ return rest+}++/** A credential resolver double: password rides the profile, keys come from the plan. */+class StubResolver {+ constructor(private readonly plan: {+ host?: string+ port?: number+ username?: string+ keys?: Array<{ privateKey: string, passphrase?: string }>+ } = {}) {}++ async resolve(input: MachineProfile): Promise<{+ host: string+ port: number+ username: string+ password?: string+ keys: Array<{ privateKey: string, passphrase?: string }>+ }> {+ const password = input.password === undefined || input.password === '' ? undefined : input.password+ return {+ host: this.plan.host ?? input.host,+ port: this.plan.port ?? input.port,+ username: this.plan.username ?? input.user,+ keys: this.plan.keys ?? [],+ ...password === undefined ? {} : { password },+ }+ }+}++type HostVerifier = (key: Buffer, verify: (valid: boolean) => void) => void++class FakeClient extends EventEmitter {+ connectConfig: Record<string, unknown> | undefined+ hostKeyAccepted: boolean | undefined+ ended = false+ execError: Error | undefined+ forwardError: Error | undefined+ /** When true, an opened exec stream never emits close (a hung command). */+ execHang = false+ /** When set, the exec stream emits this error instead of data/close. */+ streamError: Error | undefined++ constructor(+ private readonly mode: 'ready' | 'error',+ private readonly errorMessage: string,+ ) {+ super()+ }++ connect(config: Record<string, unknown>): this {+ this.connectConfig = config+ const hostVerifier = config.hostVerifier as HostVerifier | undefined+ const finish = (): void => {+ if (this.mode === 'error') {+ queueMicrotask(() => this.emit('error', new Error(this.errorMessage)))+ }+ else {+ queueMicrotask(() => this.emit('ready'))+ }+ }+ if (hostVerifier === undefined) {+ finish()+ }+ else {+ hostVerifier(Buffer.from('host-key-bytes'), (valid) => {+ this.hostKeyAccepted = valid+ finish()+ })+ }+ return this+ }++ exec(_command: string, callback: (error: Error | undefined, stream?: unknown) => void): this {+ queueMicrotask(() => {+ if (this.execError !== undefined) {+ callback(this.execError)+ return+ }+ const stream = new EventEmitter() as EventEmitter & { exitCode?: number | null }+ this.lastStream = stream+ callback(undefined, stream)+ if (this.execHang)+ return+ if (this.streamError !== undefined) {+ queueMicrotask(() => {+ stream.emit('error', this.streamError)+ stream.emit('close', null)+ })+ return+ }+ queueMicrotask(() => {+ stream.emit('data', Buffer.from('hello'))+ stream.emit('stderr', Buffer.from('oops'))+ stream.emit('close', 0)+ })+ })+ return this+ }++ /** The most recent exec stream (so end() can close it like a real channel). */+ lastStream: EventEmitter | undefined++ forwardOut(+ _srcIP: string,+ _srcPort: number,+ _dstIP: string,+ _dstPort: number,+ callback: (error: Error | undefined, channel?: unknown) => void,+ ): this {+ queueMicrotask(() => {+ if (this.forwardError !== undefined) {+ callback(this.forwardError)+ return+ }+ callback(undefined, new PassThrough())+ })+ return this+ }++ end(): void {+ this.ended = true+ // A real connection close settles the open channel too.+ if (this.lastStream !== undefined)+ this.lastStream.emit('close', null)+ this.emit('close')+ }+}++const { fakeClientFactory, fakeClientInstances } = vi.hoisted(() => {+ const instances: FakeClient[] = []+ function fakeClientFactory(mode: 'ready' | 'error', message: string): FakeClient {+ const client = new FakeClient(mode, message)+ instances.push(client)+ return client+ }+ return {+ fakeClientFactory,+ fakeClientInstances: instances,+ }+})++vi.mock('ssh2', () => {+ return {+ Client: vi.fn(fakeClientFactory),+ }+})++vi.mock('node:net', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:net')>()+ return { ...actual, createServer: vi.fn(actual.createServer) }+})++function lastClient(): FakeClient {+ const client = fakeClientInstances[fakeClientInstances.length - 1]+ if (client === undefined)+ throw new Error('no fake client created')+ return client+}++type AuthHandler = (methodsLeft: unknown, partialSuccess: boolean, callback: (value: unknown) => void) => void++/** The authHandler the transport installed on the last fake client. */+function authHandlerOf(client: FakeClient): AuthHandler {+ const handler = client.connectConfig?.authHandler+ if (typeof handler !== 'function')+ throw new Error('no authHandler in connect config')+ return handler as AuthHandler+}++/** Drive one authHandler round and return what it asks for next. */+function nextAuth(handler: AuthHandler): Promise<unknown> {+ return new Promise(resolve => handler(null, false, resolve))+}++describe('shQuote / loginShell', () => {+ it('wraps commands in a login-shell sh -c', () => {+ expect(loginShell('echo hi')).toBe('sh -lc \'echo hi\'')+ })++ it('escapes embedded single quotes', () => {+ expect(shQuote('it\'s')).toBe(`'it'\\''s'`)+ expect(loginShell('echo it\'s')).toBe('sh -lc \'echo it\'\\\'\'s\'')+ })+})++describe('ssh2Transport', () => {+ it('connects with password auth and resolves on ready', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ expect(session).toBeDefined()+ const client = lastClient()+ expect(client.connectConfig).toMatchObject({+ host: '10.0.0.1',+ port: 22,+ username: 'root',+ readyTimeout: 15000,+ })+ expect(client.hostKeyAccepted).toBe(true)+ await session.close()+ expect(client.ended).toBe(true)+ })++ it('tries the resolved keys first, then the stored password, then gives up', async () => {+ const resolver = new StubResolver({+ keys: [{ privateKey: 'KEY-A' }, { privateKey: 'KEY-B', passphrase: 'PASS' }],+ })+ const transport = new Ssh2Transport(15000, resolver)+ const session = await transport.connect(profile, () => true)+ const client = lastClient()+ const handler = authHandlerOf(client)+ expect(await nextAuth(handler)).toEqual({ type: 'publickey', username: 'root', key: 'KEY-A' })+ expect(await nextAuth(handler)).toEqual({ type: 'publickey', username: 'root', key: 'KEY-B', passphrase: 'PASS' })+ expect(await nextAuth(handler)).toEqual({ type: 'password', username: 'root', password: 'sekrit' })+ expect(await nextAuth(handler)).toBe(false)+ await session.close()+ })++ it('tries only keys when no password is stored', async () => {+ const resolver = new StubResolver({ keys: [{ privateKey: 'KEY', passphrase: 'PASS' }] })+ const transport = new Ssh2Transport(15000, resolver)+ const session = await transport.connect(withoutPassword(profile), () => true)+ const handler = authHandlerOf(lastClient())+ expect(await nextAuth(handler)).toEqual({ type: 'publickey', username: 'root', key: 'KEY', passphrase: 'PASS' })+ expect(await nextAuth(handler)).toBe(false)+ await session.close()+ })++ it('gives up immediately when nothing resolves', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(withoutPassword(profile), () => true)+ expect(await nextAuth(authHandlerOf(lastClient()))).toBe(false)+ await session.close()+ })++ it('connects to the resolver-resolved host, port, and user', async () => {+ const resolver = new StubResolver({ host: '10.0.0.9', port: 2222, username: 'deploy' })+ const transport = new Ssh2Transport(15000, resolver)+ const session = await transport.connect(profile, () => true)+ expect(lastClient().connectConfig).toMatchObject({ host: '10.0.0.9', port: 2222, username: 'deploy' })+ await session.close()+ })++ it('rejects when the resolver fails', async () => {+ const failing = {+ async resolve() {+ throw new Error('config read failed')+ },+ }+ const transport = new Ssh2Transport(15000, failing as never)+ await expect(transport.connect(profile, () => true)).rejects.toThrow('config read failed')+ })++ it('rejects on transport errors', async () => {+ const { Client } = await import('ssh2')+ vi.mocked(Client).mockImplementationOnce(() => fakeClientFactory('error', 'ECONNREFUSED'))+ const transport = new Ssh2Transport(15000, new StubResolver())+ await expect(transport.connect(profile, () => true)).rejects.toThrow('ECONNREFUSED')+ })++ it('rejects when already aborted', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const controller = new AbortController()+ controller.abort()+ await expect(transport.connect(profile, () => true, controller.signal)).rejects.toThrow()+ })++ it('aborts an in-flight handshake', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const controller = new AbortController()+ const pending = transport.connect(profile, () => true, controller.signal)+ controller.abort()+ await expect(pending).rejects.toThrow()+ })++ it('propagates a string abort reason', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const controller = new AbortController()+ controller.abort('caller gave up')+ await expect(transport.connect(profile, () => true, controller.signal)).rejects.toThrow('caller gave up')+ })++ it('propagates an arbitrary abort reason', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const controller = new AbortController()+ controller.abort({ code: 'custom' })+ await expect(transport.connect(profile, () => true, controller.signal)).rejects.toThrow('This operation was aborted')+ })++ it('accepts a synchronous verifier verdict', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => false)+ expect(lastClient().hostKeyAccepted).toBe(false)+ await session.close()+ })++ it('accepts an asynchronous verifier verdict through the callback', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, async () => true)+ expect(lastClient().hostKeyAccepted).toBe(true)+ await session.close()+ })++ it('rejects when an asynchronous verifier fails', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, async () => {+ throw new Error('verifier blew up')+ })+ expect(lastClient().hostKeyAccepted).toBe(false)+ await session.close()+ })++ it('collects exec output and exit code', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ const result = await session.exec('uname -srm')+ expect(result.code).toBe(0)+ expect(result.stdout).toBe('hello')+ expect(result.stderr).toBe('oops')+ await session.close()+ })++ it('rejects exec when the channel cannot open', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ lastClient().execError = new Error('channel open failure')+ await expect(session.exec('x')).rejects.toThrow('channel open failure')+ await session.close()+ })++ it('rejects exec with a deadline even when the channel cannot open', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ lastClient().execError = new Error('channel open failure')+ await expect(session.exec('x', { timeoutMs: 1000 })).rejects.toThrow('channel open failure')+ await session.close()+ })++ it('clears the deadline when a command finishes normally', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ const result = await session.exec('x', { timeoutMs: 1000 })+ expect(result.code).toBe(0)+ await session.close()+ })++ it('rejects exec when the stream itself errors', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ lastClient().streamError = new Error('stream reset')+ await expect(session.exec('x')).rejects.toThrow('stream reset')+ await session.close()+ })++ it('rejects exec on a stream error with a deadline pending', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ lastClient().streamError = new Error('stream reset')+ await expect(session.exec('x', { timeoutMs: 1000 })).rejects.toThrow('stream reset')+ await session.close()+ })++ it('streams stdout through the onData tap', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ const chunks: string[] = []+ const result = await session.exec('x', { onData: chunk => chunks.push(chunk) })+ expect(chunks).toEqual(['hello'])+ expect(result.stdout).toBe('hello')+ await session.close()+ })++ it('times out a hung command and closes the connection', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ lastClient().execHang = true+ await expect(session.exec('slow', { timeoutMs: 10 })).rejects.toThrow(/timed out after 10 ms/)+ expect(lastClient().ended).toBe(true)+ })++ it('forwards the remote port to a loopback listener', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ const tunnel = await session.openTunnel(3080)+ expect(tunnel.localPort).toBeGreaterThan(0)+ await tunnel.close()+ await session.close()+ })++ it('pipes real socket traffic through the tunnel', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ const tunnel = await session.openTunnel(3080)+ const socket = tcpConnect(tunnel.localPort, '127.0.0.1')+ await new Promise<void>(resolve => socket.once('connect', () => resolve()))+ socket.write('ping')+ socket.end()+ socket.resume()+ await new Promise<void>(resolve => socket.once('close', () => resolve()))+ await tunnel.close()+ await session.close()+ })++ it('destroys open sockets when the tunnel closes', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ const tunnel = await session.openTunnel(3080)+ const socket = tcpConnect(tunnel.localPort, '127.0.0.1')+ await new Promise<void>(resolve => socket.once('connect', () => resolve()))+ await new Promise(resolve => setTimeout(resolve, 20))+ await tunnel.close()+ await new Promise<void>(resolve => socket.once('close', () => resolve()))+ await session.close()+ })++ it('destroys the client socket when the tunnel channel fails', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ const tunnel = await session.openTunnel(3080)+ lastClient().forwardError = new Error('tunnel closed')+ const socket = tcpConnect(tunnel.localPort, '127.0.0.1')+ await new Promise<void>((resolve, reject) => {+ socket.once('connect', () => resolve())+ socket.once('error', reject)+ })+ await new Promise<void>(resolve => socket.once('close', () => resolve()))+ await tunnel.close()+ await session.close()+ })++ it('rejects the tunnel when the local listener fails to bind', async () => {+ const net = await import('node:net')+ vi.mocked(net.createServer).mockImplementationOnce(() => {+ const server = new Server()+ queueMicrotask(() => server.emit('error', new Error('EADDRINUSE')))+ return server+ })+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ await expect(session.openTunnel(3080)).rejects.toThrow('EADDRINUSE')+ await session.close()+ })++ it('fires the closed callback once when the connection drops', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ const callback = vi.fn()+ session.onClosed(callback)+ lastClient().emit('close')+ expect(callback).toHaveBeenCalledTimes(1)+ lastClient().emit('close')+ expect(callback).toHaveBeenCalledTimes(1)+ await session.close()+ })++ it('fires the closed callback immediately for an already-closed session', async () => {+ const transport = new Ssh2Transport(15000, new StubResolver())+ const session = await transport.connect(profile, () => true)+ lastClient().emit('close')+ const callback = vi.fn()+ session.onClosed(callback)+ expect(callback).toHaveBeenCalledTimes(1)+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.ts b/packages/dsh-tauri-ssh/src/host/service/transport.tsnew file mode 100644index 00000000..ae78a0b8--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/transport.ts@@ -0,0 +1,321 @@+/**+ * SSH transport seam and its ssh2 implementation. The manager depends on the+ * narrow interfaces here — connect, exec, tunnel, close — so tests inject a+ * fake transport and never touch the network.+ * @module dsh-tauri-ssh/host/service/transport+ */++import type { Buffer } from 'node:buffer'+import type { AddressInfo, Server } from 'node:net'+import type { ConnectConfig } from 'ssh2'+import type { MachineProfile } from '../types/index.js'+import type { ResolvedSshAuth } from './ssh-config.js'+import { createServer } from 'node:net'+import { Client } from 'ssh2'++/** The credential-resolution face the transport needs (SshConfigResolver implements it). */+export interface SshCredentialsResolver {+ resolve: (profile: MachineProfile) => Promise<ResolvedSshAuth>+}++/** One completed remote command. */+export interface SshExecResult {+ /** Exit code; null when the remote side reported none. */+ code: number | null+ stdout: string+ stderr: string+}++/** Optional exec behavior: a deadline and/or a streaming stdout tap. */+export interface SshExecOptions {+ /** Abort the command after this many milliseconds (closes the connection). */+ timeoutMs?: number+ /** Receive stdout chunks as they arrive (long-running commands, logs). */+ onData?: (chunk: string) => void+}++/** A local loopback listener forwarding into the SSH tunnel. */+export interface SshTunnelHandle {+ /** The bound loopback port (0 = ephemeral, read from the server). */+ localPort: number+ /** Close the listener; in-flight forwarded connections are aborted. */+ close: () => Promise<void>+}++/** One authenticated SSH session. */+export interface SshSession {+ /**+ * Run one command through the remote login shell.+ * @param command - the full command line.+ * @param options - optional deadline and streaming stdout tap.+ * @returns the collected result.+ */+ exec: (command: string, options?: SshExecOptions) => Promise<SshExecResult>+ /**+ * Forward a remote loopback port to a new local loopback listener+ * (`ssh -L` semantics).+ * @param remotePort - the remote 127.0.0.1 port to reach.+ * @returns the local listener handle.+ */+ openTunnel: (remotePort: number) => Promise<SshTunnelHandle>+ /**+ * Register the session-closed callback (connection dropped, server went+ * away, or {@link close} ran).+ * @param callback - fired exactly once.+ */+ onClosed: (callback: () => void) => void+ /** Close the session; idempotent. */+ close: () => Promise<void>+}++/** Transport factory: authenticate one machine and return its session. */+export interface SshTransport {+ /**+ * @param profile - the machine profile to connect.+ * @param hostKeyVerifier - TOFU host-key gate; may be async (the ssh2+ * callback form waits for the verdict).+ * @param signal - aborts the handshake.+ * @returns the authenticated session.+ */+ connect: (+ profile: MachineProfile,+ hostKeyVerifier: (hostKey: Buffer) => boolean | Promise<boolean>,+ signal?: AbortSignal,+ ) => Promise<SshSession>+}++/** Wrap one string for safe inclusion in a remote shell command line. */+export function shQuote(value: string): string {+ return `'${value.replace(/'/gu, `'\\''`)}'`+}++/** Build the `sh -lc <command>` wrapper used for every remote command. */+export function loginShell(command: string): string {+ return `sh -lc ${shQuote(command)}`+}++/**+ * ssh2-backed transport. One `Client` per session; exec and tunnel run over+ * the shared connection. Credentials come from the injected+ * {@link SshCredentialsResolver}: the host's own `~/.ssh` (config aliases,+ * IdentityFiles, default keys) with the profile's stored password/passphrase+ * as fallbacks — the connection behaves like a local `ssh` invocation.+ */+export class Ssh2Transport implements SshTransport {+ /**+ * @param readyTimeoutMs - handshake deadline for {@link Client.connect}.+ * @param resolver - the `~/.ssh` credential resolver (host, port, user, keys).+ */+ constructor(+ private readonly readyTimeoutMs: number,+ private readonly resolver: SshCredentialsResolver,+ ) {}++ async connect(+ profile: MachineProfile,+ hostKeyVerifier: (hostKey: Buffer) => boolean | Promise<boolean>,+ signal?: AbortSignal,+ ): Promise<SshSession> {+ return new Promise<SshSession>((resolve, reject) => {+ if (signal?.aborted) {+ reject(abortError(signal))+ return+ }+ const client = new Client()+ const onAbort = (): void => {+ client.end()+ reject(abortError(signal as AbortSignal))+ }+ if (signal !== undefined)+ signal.addEventListener('abort', onAbort, { once: true })+ const settle = (fn: () => void): void => {+ signal?.removeEventListener('abort', onAbort)+ fn()+ }+ client.on('ready', () => {+ settle(() => resolve(new Ssh2Session(client)))+ })+ client.on('error', (error) => {+ settle(() => reject(error))+ })+ void this.resolver.resolve(profile).then((auth) => {+ // Try every resolved identity in order, then the stored password —+ // the same preference order as OpenSSH (publickey before password).+ // ssh2 parses each key itself and skips invalid ones, so a bad or+ // passphrase-locked key never aborts the attempt. Each credential is+ // offered at most once; the handler then gives up.+ let keyIndex = 0+ let passwordOffered = false+ const authHandler: NonNullable<ConnectConfig['authHandler']> = (_methodsLeft, _partialSuccess, callback) => {+ const key = auth.keys[keyIndex]+ if (key !== undefined) {+ keyIndex += 1+ callback({+ type: 'publickey',+ username: auth.username,+ key: key.privateKey,+ ...key.passphrase === undefined ? {} : { passphrase: key.passphrase },+ })+ }+ else if (auth.password !== undefined && !passwordOffered) {+ passwordOffered = true+ callback({ type: 'password', username: auth.username, password: auth.password })+ }+ else {+ // `false` signals "no more methods" at runtime; the published+ // NextAuthHandler type omits it.+ callback(false as never)+ }+ }+ client.connect({+ host: auth.host,+ port: auth.port,+ username: auth.username,+ readyTimeout: this.readyTimeoutMs,+ // Keep the connection alive during long remote commands (dsh+ // installs, health polling): default ssh2 keepalives are off, and+ // idle NAT/firewall state would otherwise drop a 10-minute install.+ keepaliveInterval: 10_000,+ keepaliveCountMax: 3,+ authHandler,+ // ssh2 accepts a synchronous boolean return OR the verify-callback+ // form; always driving the callback keeps async verifiers uniform.+ hostVerifier: (key: Buffer, verify: (valid: boolean) => void): void => {+ const verdict = hostKeyVerifier(key)+ if (verdict instanceof Promise) {+ void verdict.then(verify, () => verify(false))+ }+ else {+ verify(verdict)+ }+ },+ })+ }, reject)+ })+ }+}++/** The ssh2 session face over one authenticated `Client`. */+class Ssh2Session implements SshSession {+ private readonly closed = new Set<() => void>()+ private closedFired = false++ constructor(private readonly client: Client) {+ this.client.on('close', () => {+ if (this.closedFired)+ return+ this.closedFired = true+ for (const callback of this.closed) callback()+ this.closed.clear()+ })+ }++ exec(command: string, options?: SshExecOptions): Promise<SshExecResult> {+ return new Promise<SshExecResult>((resolve, reject) => {+ let settled = false+ const timer = options?.timeoutMs === undefined+ ? undefined+ : setTimeout(() => {+ /* v8 ignore next 3 -- race guard: the timer always loses to close/error, which clear it */+ if (settled)+ return+ settled = true+ // Closing the connection kills the remote channel (and its process)+ // and settles any in-flight close events.+ this.client.end()+ reject(new Error(`remote command timed out after ${options.timeoutMs} ms`))+ }, options.timeoutMs)+ this.client.exec(loginShell(command), (error, stream) => {+ if (error !== undefined) {+ /* v8 ignore next 3 -- race guard: an exec-open error either settles first or follows a timeout */+ if (!settled) {+ settled = true+ if (timer !== undefined)+ clearTimeout(timer)+ reject(error)+ }+ return+ }+ let stdout = ''+ let stderr = ''+ stream.on('data', (chunk: Buffer) => {+ const text = chunk.toString('utf8')+ stdout += text+ options?.onData?.(text)+ })+ stream.on('stderr', (chunk: Buffer) => {+ stderr += chunk.toString('utf8')+ })+ stream.on('close', (code: number | null) => {+ if (settled)+ return+ settled = true+ if (timer !== undefined)+ clearTimeout(timer)+ resolve({ code, stdout, stderr })+ })+ stream.on('error', (streamError: Error) => {+ /* v8 ignore next -- race guard: a stream error either settles first or follows a timeout */+ if (settled)+ return+ settled = true+ if (timer !== undefined)+ clearTimeout(timer)+ reject(streamError)+ })+ })+ })+ }++ openTunnel(remotePort: number): Promise<SshTunnelHandle> {+ return new Promise<SshTunnelHandle>((resolve, reject) => {+ const sockets = new Set<import('node:net').Socket>()+ const server: Server = createServer((socket) => {+ sockets.add(socket)+ socket.on('close', () => sockets.delete(socket))+ this.client.forwardOut('127.0.0.1', 0, '127.0.0.1', remotePort, (error, channel) => {+ if (error !== undefined) {+ socket.destroy()+ return+ }+ socket.pipe(channel).pipe(socket)+ })+ })+ server.on('error', reject)+ server.listen(0, '127.0.0.1', () => {+ const { port } = server.address() as AddressInfo+ resolve({+ localPort: port,+ close: () => new Promise<void>((closeResolve) => {+ server.close(() => closeResolve())+ // A half-open forwarded socket must not park the close forever.+ for (const socket of sockets) socket.destroy()+ }),+ })+ })+ })+ }++ onClosed(callback: () => void): void {+ if (this.closedFired) {+ callback()+ return+ }+ this.closed.add(callback)+ }++ close(): Promise<void> {+ this.client.end()+ return Promise.resolve()+ }+}++/** Mirror fetch's abort rejection: the signal's reason when present, else a DOMException-style AbortError. */+function abortError(signal: AbortSignal): Error {+ const reason: unknown = signal.reason+ if (reason instanceof Error)+ return reason+ if (typeof reason === 'string')+ return new Error(reason)+ return new Error('This operation was aborted')+}diff --git a/packages/dsh-tauri-ssh/src/host/storage/index.ts b/packages/dsh-tauri-ssh/src/host/storage/index.tsnew file mode 100644index 00000000..45c03aae--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/storage/index.ts@@ -0,0 +1,128 @@+/**+ * Plugin config and the `ssh-machines` settings-namespace schema. The+ * namespace stores a dict of machine profiles keyed by machine id — a dict+ * (not an array) so a redacted client can add, edit, and delete one machine+ * through `settings.update` deep-merge and `settings.mutate` path-unset+ * without ever re-supplying (or deleting) secrets it never saw.+ * @module dsh-tauri-ssh/host/storage+ */++import type { MachineProfile } from '../types/index.js'+import z from 'schemastery'+import { MachineId } from '../types/index.js'++/** One settings-namespace key (the harness brands these; the wire treats them as strings). */+export type SettingsNamespace = string & { readonly __namespace: unique symbol }++/** Brand a settings namespace key. */+export function settingsNamespace(name: string): SettingsNamespace {+ return name as SettingsNamespace+}++/** Settings namespace key owning the machine profile dict. */+export const MACHINES_NAMESPACE = settingsNamespace('ssh-machines')++/** Default TCP port of the remote `dsh web` instance (loopback). */+export const DEFAULT_REMOTE_PORT = 3080++/** Default SSH transport port. */+export const DEFAULT_SSH_PORT = 22++/**+ * One machine profile schema: the settings-namespace member shape. Credential+ * fields are `role('secret')` positions — redacted from every wire surface,+ * present in the owner scope's resolved value. Authentication itself runs on+ * the host's `~/.ssh`; the stored fields are only the optional fallbacks.+ */+export const MachineSchema = z.object({+ id: z.string().required(),+ name: z.string().required(),+ host: z.string().required(),+ port: z.number().default(DEFAULT_SSH_PORT),+ user: z.string().required(),+ password: z.string().role('secret'),+ passphrase: z.string().role('secret'),+ remotePort: z.number().default(DEFAULT_REMOTE_PORT),+ startCommand: z.string(),+ color: z.string(),+ tintBorder: z.boolean(),+})++/** The whole `ssh-machines` namespace value: a dict of profiles by machine id. */+export const MachinesSchema = z.object({+ machines: z.dict(MachineSchema).default({}),+}) as unknown as z<MachinesValue>++/** Resolved value shape of the `ssh-machines` namespace. */+export interface MachinesValue {+ machines: Record<string, MachineProfile>+}++/**+ * Validated plugin config. Timeouts are deployment-varying choices, never+ * hardcoded tunables.+ */+export interface Config {+ /** SSH handshake/authentication deadline in milliseconds. */+ connectTimeoutMs: number+ /** Per-probe deadline of the remote-instance health check in milliseconds. */+ healthCheckTimeoutMs: number+ /** Pause between health-check probes while waiting for the instance. */+ healthPollIntervalMs: number+ /** How many probes run before the bootstrap attempt is declared failed. */+ healthPollAttempts: number+ /** Override for the TOFU known-hosts file (defaults under the harness home). */+ knownHostsPath?: string+ /** Override for the `~/.ssh` directory the credentials resolve against. */+ sshDir?: string+ /** Default remote `dsh web` port for machines that do not override it. */+ remotePort?: number+ /**+ * Default remote-instance start command for machines without their own+ * override; `{port}` is replaced with the machine's remote port. Covers+ * the discovered `~/.ssh/config` aliases, which cannot carry per-machine+ * overrides.+ */+ startCommand?: string+ /**+ * Git repository URL the one-click install clones from. Defaults to the+ * official GitHub repository; set your own fork, an internal mirror, or a+ * private repository (a credential-bearing URL works). The clone happens on+ * the remote machine, so the remote must be able to reach and read it.+ */+ installRepo?: string+ /** Git ref (branch/tag) the one-click install checks out; defaults to the repository's default branch. */+ installRef?: string+ /** Deadline for one remote dsh install (clone + pnpm install + build). */+ installTimeoutMs?: number+}++/** Plugin config schema; schemastery fills defaults before construction. */+export const ConfigSchema: z<Config> = z.object({+ connectTimeoutMs: z.number().default(15_000),+ healthCheckTimeoutMs: z.number().default(3_000),+ healthPollIntervalMs: z.number().default(1_000),+ healthPollAttempts: z.number().default(30),+ knownHostsPath: z.string(),+ sshDir: z.string(),+ remotePort: z.number().default(DEFAULT_REMOTE_PORT),+ startCommand: z.string(),+ installRepo: z.string(),+ installRef: z.string(),+ installTimeoutMs: z.number().default(1_800_000),+})++/** Normalize a resolved namespace value into a machine profile map keyed by id. */+export function machinesFromValue(value: MachinesValue): Map<MachineId, MachineProfile> {+ const profiles = new Map<MachineId, MachineProfile>()+ for (const [key, profile] of Object.entries(value.machines)) {+ const id = MachineId(key)+ if (profile.id !== key) {+ throw new Error(+ `ssh-machines: machine "${key}" carries id "${profile.id}"; the dict key must equal the profile id`,+ )+ }+ profiles.set(id, { ...profile, id })+ }+ return profiles+}diff --git a/packages/dsh-tauri-ssh/src/host/types/index.ts b/packages/dsh-tauri-ssh/src/host/types/index.tsnew file mode 100644index 00000000..cf3da833--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/types/index.ts@@ -0,0 +1,213 @@+/**+ * Public type vocabulary of the SSH remote-machine plugin: the `MachineId`+ * brand, the stored machine profile, its redacted view, connection status,+ * the tunnel link, the typed failure vocabulary, and the structural host+ * services the plugin consumes (the DSH packages providing them are private+ * to the harness, so the plugin declares just the surface it touches).+ * @module dsh-tauri-ssh/host/types+ */++import type { IncomingMessage, ServerResponse } from 'node:http'+import type z from 'schemastery'++/** Identifies one SSH machine profile. A generated uuid, never the host name: hosts are not unique. */+export type MachineId = string & { readonly __machineId: unique symbol }++/**+ * Brand a string as a {@link MachineId}.+ * @param id - the raw machine id string.+ * @returns the same string, branded (a compile-time cast — no runtime cost).+ */+// eslint-disable-next-line ts/no-redeclare -- 品牌类型惯用法:值与类型同名+export function MachineId(id: string): MachineId {+ return id as MachineId+}++/**+ * One stored SSH machine profile: the `ssh-machines` settings-namespace+ * value shape. Credentials are deliberately sparse: authentication runs on+ * the host's own `~/.ssh` (config aliases, `IdentityFile`s, default keys),+ * so only the optional fallback secrets live here. Secret fields are+ * schema-declared `role('secret')` positions — they never ride a redacted+ * wire surface, only the owner scope's resolved in-process value.+ */+export interface MachineProfile {+ /** Stable profile id (generated uuid). */+ id: MachineId+ /** Display name (duplicates allowed). */+ name: string+ /** SSH server host name, IP literal, or a `~/.ssh/config` `Host` alias. */+ host: string+ /** SSH server TCP port; a config `Port` override wins when present. */+ port: number+ /** Login user name; empty means "resolve from config or the OS user". */+ user: string+ /** Password credential; secret. Optional fallback when no key works. */+ password?: string+ /** Passphrase unlocking the `~/.ssh` identity files; secret. Optional. */+ passphrase?: string+ /** TCP port the remote `dsh web` instance listens on (loopback). */+ remotePort: number+ /** Command that starts the remote instance; defaults to `dsh web --host 127.0.0.1 --port <remotePort>`. */+ startCommand?: string+ /** Optional identity color (any CSS color) shown as the machine's pip in the UI. */+ color?: string+ /** Whether the identity color also tints the machine card's border in the UI. */+ tintBorder?: boolean+}++/**+ * Redacted view of one machine profile: secrets replaced by presence flags.+ * This is the only profile shape that may cross a wire surface.+ */+export interface MachineView {+ id: MachineId+ name: string+ host: string+ port: number+ user: string+ /** Whether the profile currently holds a password (the value itself never rides). */+ hasPassword: boolean+ /** Whether the profile currently holds a key passphrase (the value itself never rides). */+ hasPassphrase: boolean+ remotePort: number+ startCommand?: string+ color?: string+ tintBorder?: boolean+}++/** One machine row as the settings page writes it: config fields only, no secrets. */+export interface MachineSaveRow {+ name: string+ host: string+ port: number+ user: string+ remotePort: number+ startCommand?: string+ color?: string+ tintBorder?: boolean+}++/** Secret values the settings page writes (write-only direction; absent = keep stored). */+export interface MachineSecretWrite {+ password?: string+ passphrase?: string+}++/** Live connection state of one machine. */+export type SshConnectionState = 'disconnected' | 'connecting' | 'connected'++/** One progress phase of a connection-plane operation, shown live in the UI. */+export type SshProgressPhase = 'handshake' | 'starting' | 'probing' | 'installing'++/** Structured progress of an in-flight connection-plane operation. */+export interface SshProgress {+ phase: SshProgressPhase+ /** Progress position (e.g. health-probe attempt number). */+ attempt?: number+ /** Progress total (e.g. health-probe attempt budget). */+ total?: number+ /** Recent streaming output of the operation (the install log), newest last. */+ log?: string+}++/** Transport-level status of one machine. */+export interface SshMachineStatus {+ machineId: MachineId+ state: SshConnectionState+ /** Local loopback URL of the SSH tunnel to the remote instance; present while connected. */+ tunnelBaseUrl?: string+ /** Operator-facing failure description of the last failed transition; absent while healthy. */+ lastError?: string+ /** Whether the last failure was "dsh not installed on the remote" (offers install). */+ dshMissing?: boolean+ /** Live progress of the in-flight operation; absent while idle. */+ progress?: SshProgress+}++/** A live machine link: the id and the tunnel base URL. */+export interface SshLink {+ machineId: MachineId+ /** `http://127.0.0.1:<localPort>` — loopback only, never exposed to remote clients. */+ tunnelBaseUrl: string+}++/** Outcome of a one-shot connection test. */+export type SshTestResult+ = | { ok: true, banner: string }+ | { ok: false, message: string }++/** Outcome of a one-shot remote dsh install. */+export interface SshInstallResult {+ /** Absolute path of the installed `dsh` binary as the remote sees it. */+ dshPath: string+ /** Whether the local DEEPSEEK_API_KEY was copied to the remote `~/.dsh/.env`. */+ credentialsCopied: boolean+ /** Operator-facing description when the credentials copy itself failed. */+ credentialsError?: string+}++/** Closed failure vocabulary of the ssh primitives. */+export type SshErrorCode+ = | 'machine-not-found'+ | 'machine-connect-failed'+ | 'machine-bootstrap-failed'+ | 'machine-dsh-missing'+ | 'machine-install-failed'+ | 'machine-ssh-error'++/** Typed failure thrown by ssh primitives so consumers map business codes without string matching. */+export class SshError extends Error {+ /**+ * @param code - closed business code of the failure.+ * @param machineId - the machine the failure is about.+ * @param message - operator-facing description.+ */+ constructor(readonly code: SshErrorCode, readonly machineId: MachineId, message: string) {+ super(message)+ this.name = 'SshError'+ }+}++/** The webserver route shape this plugin registers (a subset of the harness's WebRoute). */+export interface HostWebRoute {+ kind: 'exact' | 'prefix'+ /** Absolute pathname, no trailing slash. */+ path: string+ /** Owns the full response lifecycle (may hold the response open, e.g. SSE). */+ handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>+}++/** The settings namespace scope this plugin registers (a subset of dsh-settings' SettingsScope). */+export interface HostSettingsScope<T> {+ /** The current resolved namespace value. */+ get: () => T+ /** Subscribe to value changes; returns an unsubscribe. */+ watch: (callback: (next: T, prev: T) => void) => () => void+ /** Merge a patch into the user section and persist (schema-validated). */+ update: (patch: object) => Promise<void>+ /** Replace the user section wholesale (absent keys re-inherit defaults). */+ replace: (section: object) => Promise<void>+}++/** The settings service surface this plugin needs. */+export interface HostSettings {+ register: <T>(ns: string, schema: z<T>, options?: { base?: T, applies?: 'live' | 'restart' }) => HostSettingsScope<T>+}++/** The webserver service surface this plugin needs. */+export interface HostWebServer {+ register: (route: HostWebRoute) => () => void+}++/**+ * The host context this plugin's apply receives: the settings seam (namespace)+ * and the webserver (route mount), plus the teardown-effect seat. Structural —+ * the harness's real context duck-types onto it.+ */+export interface SshHostContext {+ settings: HostSettings+ webServer: HostWebServer+ /** Register a teardown effect (narrow cordis surface). */+ effect: (execute: () => () => void, label?: string) => unknown+}diff --git a/packages/dsh-tauri-ssh/src/index.ts b/packages/dsh-tauri-ssh/src/index.tsnew file mode 100644index 00000000..ffb8f13d--- /dev/null+++ b/packages/dsh-tauri-ssh/src/index.ts@@ -0,0 +1,20 @@+/**+ * The DSH remote-machine host plugin. Registers the `ssh-machines` settings+ * namespace, owns the SSH connection manager (TOFU host keys, remote `dsh+ * web` auto-start, loopback tunnels), and mounts the same-origin `/api-ssh`+ * route on `ctx.webServer` for the settings page. No upstream DSH source is+ * touched: every integration is a documented cordis extension point.+ *+ * 三层目录(host / shared):+ * - index.ts(本文件) public barrel(只保留导出面);+ * - shared/constants 跨 half 协议常量(插件名 / API 前缀);+ * - host/ Node half:routes(/api-ssh 路由)/ storage+ * (ssh-machines 命名空间 schema 与插件配置)/+ * service(manager 状态机、bootstrap 远端保障、+ * ssh-config 凭据解析、transport ssh2 传输、+ * host-keys TOFU 存储)/ types / apply。+ * @module dsh-tauri-ssh+ */++export { apply, Config, default, inject, name, SshRemoteService } from './host/apply.js'+export { SSH_API_PREFIX } from './shared/constants.js'diff --git a/packages/dsh-tauri-ssh/src/shared/constants.ts b/packages/dsh-tauri-ssh/src/shared/constants.tsnew file mode 100644index 00000000..eacb90b5--- /dev/null+++ b/packages/dsh-tauri-ssh/src/shared/constants.ts@@ -0,0 +1,15 @@+/**+ * Cross-half protocol constants of the SSH remote-machine plugin pair+ * (`dsh-tauri-ssh` host / `dsh-tauri-ssh-ui` client). Both halves and the+ * docs reference these identifiers; centralizing them prevents drift.+ * @module dsh-tauri-ssh/shared/constants+ */++/** Cordis plugin name / loader id of the host half. */+export const SSH_PLUGIN_NAME = 'dsh-tauri-ssh'++/**+ * The same-origin connection-plane route the host half mounts on+ * `ctx.webServer` (and the client half POSTs to). Loopback-only by contract.+ */+export const SSH_API_PREFIX = '/api-ssh'diff --git a/packages/dsh-tauri-ssh/tsconfig.json b/packages/dsh-tauri-ssh/tsconfig.jsonnew file mode 100644index 00000000..2cae36c8--- /dev/null+++ b/packages/dsh-tauri-ssh/tsconfig.json@@ -0,0 +1,12 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "target": "es2024",+ "lib": ["ES2024"],+ "types": ["node"],+ "exactOptionalPropertyTypes": true,+ "noImplicitOverride": true,+ "noUncheckedIndexedAccess": true+ },+ "include": ["src/**/*.ts", "../../types/**/*.d.ts"]+}diff --git a/packages/dsh-tauri-ssh/tsdown.config.ts b/packages/dsh-tauri-ssh/tsdown.config.tsnew file mode 100644index 00000000..a90bae13--- /dev/null+++ b/packages/dsh-tauri-ssh/tsdown.config.ts@@ -0,0 +1,15 @@+import { defineConfig, dshExternal } from 'dsh-tauri-tsdown'++// Host-only plugin (no client half — the settings page is dsh-tauri-ssh-ui):+// one ESM entry with dts, mirroring defineDshConfig's server half.+export default defineConfig({+ outDir: 'dist',+ format: 'esm',+ outExtensions: () => ({ js: '.js' }),+ publint: true,+ external: dshExternal,+ entry: { index: 'src/index.ts' },+ dts: true,+ sourcemap: false,+ clean: true,+})diff --git a/packages/dsh-tauri-tsdown/package.json b/packages/dsh-tauri-tsdown/package.jsonindex 47c29069..ba2f2834 100644--- a/packages/dsh-tauri-tsdown/package.json+++ b/packages/dsh-tauri-tsdown/package.json@@ -13,6 +13,7 @@"typecheck": "tsc --noEmit"},"devDependencies": {+ "lightningcss": "catalog:ui","tsdown": "catalog:cli","typescript": "catalog:cli"}diff --git a/packages/dsh-tauri-tsdown/src/index.ts b/packages/dsh-tauri-tsdown/src/index.tsindex f914c600..2c10c71f 100644--- a/packages/dsh-tauri-tsdown/src/index.ts+++ b/packages/dsh-tauri-tsdown/src/index.ts@@ -117,9 +117,7 @@ export function defineDshConfig(options: DshConfigOptions = {}) {// publint's ESM/CJS default-export heuristic is inapplicable.publint: false,dts: false,- // 客户端 sourcemap 只在 watch 下产出:它会随 `files: ["dist"]` 一起进入- // `resources/node_modules`(9 个插件合计约 2.5 MB),而运行期从不加载。- sourcemap: !isWatchMode,+ sourcemap: true,minify: !isWatchMode,clean: false,...clientOptions,diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 972804ba..24db182b 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -1,8 +1,10 @@allowBuilds:'@tailwindcss/oxide': true+ cpu-features: falseedgedriver: falseesbuild: truegeckodriver: false+ ssh2: falsecatalogMode: prefer@@ -32,6 +34,8 @@ catalog:'@tauri-apps/plugin-os': ^2.3.2'@tauri-apps/plugin-store': ^2.4.4h3: 2.0.1-rc.31+ anser: ^2.3.5+ shiki: ^1.29.2valtio: ^2.3.2catalogs:@@ -102,8 +106,11 @@ catalogs:'@tauri-apps/cli': ^2.11.4'@tauri-apps/plugin-http': ^2.6.0testing:+ '@testing-library/dom': ^10.4.0+ '@testing-library/react': ^16.3.0'@vitest/coverage-v8': ^4.1.11'@wdio/tauri-service': ^1.4.0+ jsdom: ^26.1.0playwright: ^1.63.0vitest: ^4.1.11webdriverio: ^9.31.9@@ -114,11 +121,14 @@ catalogs:'@types/react': ^19.2.18'@types/react-dom': ^19.2.4'@types/semver': ^7.8.0+ '@types/ssh2': ^1.15.4ui:'@css-render/plugin-bem': ^0.15.7css-render: ^0.15.14dompurify: ^3.4.13+ lightningcss: ^1.32.0marked: ^18.0.10+ schemastery: ^3.18.0utils:'@hairy/utils': ^1.52.0citty: ^0.2.2@@ -130,6 +140,7 @@ catalogs:lodash-es: ^4.18.1ofetch: ^1.5.1pathe: ^2.0.3+ ssh2: ^1.17.0simple-git: ^3.36.0smol-toml: ^1.3.1tinyexec: ^1.3.0diff --git a/src-tauri/resources/internal-plugins.json b/src-tauri/resources/internal-plugins.jsonindex 8e7cd21f..592e68df 100644--- a/src-tauri/resources/internal-plugins.json+++ b/src-tauri/resources/internal-plugins.json@@ -75,5 +75,19 @@"name": "DSH Tauri Model Config","description": "Model selection and parameter configuration for the DeepSeek Harness desktop shell","repoUrl": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/tree/main/packages/dsh-tauri-model-config"+ },+ {+ "id": "dsh-tauri-ssh",+ "spec": "dsh-tauri-ssh",+ "name": "DSH Tauri SSH",+ "description": "Remote-machine host kernel for the desktop: SSH connection management with TOFU host keys, ~/.ssh/config discovery, remote dsh web auto-start, loopback tunnels, and the same-origin /api-ssh route.",+ "repoUrl": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-ssh"+ },+ {+ "id": "dsh-tauri-ssh-ui",+ "spec": "dsh-tauri-ssh-ui",+ "name": "DSH Tauri SSH UI",+ "description": "Settings page for SSH remote machines: machine CRUD with per-machine identity colors, connect/test/disconnect through the plugin's /api-ssh route, one-click remote dsh install, and the tunnel popup opener.",+ "repoUrl": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-ssh-ui"}]