dsh-linked-workspace 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  English · [简体中文](CHANGELOG.zh.md)
4
4
 
5
+ ## 0.20.0 — 2026-11-19
6
+
7
+ - **Host key policy**: new `hostKeyPolicy` setting — `tofu` (default: trust and remember the first key) or `strict` (refuse any key we have never seen, which also covers a man-in-the-middle on the very first connection).
8
+ - **Forget a host key**: `hosts.hostKeys` and `hosts.forgetHostKey` list the remembered authorities with their fingerprints and let you forget one so it is trusted again on the next connect.
9
+ - **Command output encoding**: new `outputEncoding` setting — `utf8` (default) or `gbk`, so `hosts.exec` on a Chinese Windows remote no longer returns mojibake (`TextDecoder`, no new dependency).
10
+ - `HOST_KEY_UNKNOWN` (409): a strict refusal now has its own error code and message instead of a generic `INTERNAL`.
11
+ - `apiRevision` 5 → 6.
5
12
  ## 0.19.0 — 2026-11-19
6
13
 
7
14
  - **Push local edits back.** `linked.plan` compares the local directory with the remote one file by file against the hash remembered from the last push, and classifies each file as added / changed / conflict / gone-upstream; the tree toolbar gained a sync button with a diff preview, and the row menu gained "push this to the remote side".
package/docs/API.md CHANGED
@@ -55,9 +55,11 @@ scope root, or absolute inside it.
55
55
  | `hosts.credentials` | `{ hostId, password?, passphrase?, privateKey?, clear? }` | `{ hostId, authType, hasCredential, hasStoredPassword }` (stores the secret in the plugin's own `ssh-credentials.json`; `clear: true` deletes it) |
56
56
  | `hosts.browse` | `{ hostId, path? }` | `{ path, parent, home, entries }` (dirs + files) |
57
57
  | `hosts.df` | `{ hostId, path? }` | `{ disk: { path, size, used, avail, percent } \| null }` (free space of the volume holding `path`; defaults to the login home) |
58
+ | `hosts.hostKeys` | `{}` | `{ entries: [{ authority, fingerprint, firstSeen, hostId?, hostName? }] }` — the keys remembered in `known_hosts.json`; `hostId` is filled in when the authority still matches a configured host |
59
+ | `hosts.forgetHostKey` | `{ hostId?/authority? }` | `{ authority, removed }` — drops the stored key (and the live connection) so the next connect trusts the host again; `settings.hostKeyPolicy` decides whether an unknown key is accepted (`tofu`, default) or refused (`strict`) |
58
60
  | `hosts.status` | `{ hostIds? }` | `{ statuses: { [hostId]: { state, reason?, message?, latencyMs?, checkedAt? } } }` (in-memory snapshot of the pool, never dials; an `error` older than 60 s is reported as `idle`; defaults to every known host of the host list plus every workspace's host id) |
59
61
  | `hosts.mkdir` | `{ hostId, path?, name }` | `{ path }` (creates `name` inside `path`; defaults to the login home; `409`/`FS_EXISTS` when it already exists) |
60
- | `hosts.exec` | `{ hostId?/linkedId?/remoteId?, command, cwd?, timeoutMs? }` | `{ hostId, hostName, workspaceId, kind, command, cwd, exitCode, stdout, stderr, stdoutBytes, stderrBytes, truncated, durationMs, startedAt, auditId }` — runs **one** non-interactive command on the remote host. Three gates: `settings.execEnabled` must be `true`, the host must be in `settings.execHostIds`, and — when `settings.execWorkspaceIds` is non-empty — the workspace must be in it. Refusals are audited too and answer `403` (`EXEC_DISABLED` / `EXEC_HOST_NOT_ALLOWED` / `EXEC_WORKSPACE_NOT_ALLOWED`); a timeout answers `504` `EXEC_TIMEOUT`, other failures `502` `EXEC_FAILED`. Output is clipped to `settings.execMaxOutputChars` per stream (default 200000, head+tail). `cwd` is resolved inside the workspace root and may not escape it. |
62
+ | `hosts.exec` | `{ hostId?/linkedId?/remoteId?, command, cwd?, timeoutMs? }` | `{ hostId, hostName, workspaceId, kind, command, cwd, exitCode, stdout, stderr, stdoutBytes, stderrBytes, truncated, durationMs, startedAt, auditId }` — runs **one** non-interactive command on the remote host. Three gates: `settings.execEnabled` must be `true`, the host must be in `settings.execHostIds`, and — when `settings.execWorkspaceIds` is non-empty — the workspace must be in it. Refusals are audited too and answer `403` (`EXEC_DISABLED` / `EXEC_HOST_NOT_ALLOWED` / `EXEC_WORKSPACE_NOT_ALLOWED`); a timeout answers `504` `EXEC_TIMEOUT`, other failures `502` `EXEC_FAILED`. Output is clipped to `settings.execMaxOutputChars` per stream (default 200000, head+tail). `cwd` is resolved inside the workspace root and may not escape it. Output is decoded with `settings.outputEncoding` (`utf8` by default, `gbk` for Chinese Windows remotes). |
61
63
  | `remote_workspaces.list` | `{}` | `{ workspaces: RemoteWorkspaceInfo[] }` |
62
64
  | `remote_workspaces.create` | `{ hostId, remotePath, name? }` | `{ workspace }` |
63
65
  | `remote_workspaces.get` | `{ id }` | `{ workspace }` |
@@ -137,18 +139,20 @@ Under `$DSH_HOME/linked-workspace/`:
137
139
 
138
140
  - `linked.json` — linked workspaces (no credentials).
139
141
  - `remote-workspaces.json` — remote workspaces (no credentials).
140
- - `settings.json` — `{ editorTheme, editorThemeFamily, editorThemeMode, fileOpenMode, autoSave, execEnabled, execHostIds, execWorkspaceIds, execTimeoutMs, execMaxOutputChars, execShell }`.
142
+ - `settings.json` — `{ editorTheme, editorThemeFamily, editorThemeMode, fileOpenMode, autoSave, execEnabled, execHostIds, execWorkspaceIds, execTimeoutMs, execMaxOutputChars, execShell, autoPushEnabled, autoPushDebounceMs, autoPushInclude, autoPushExclude, hostKeyPolicy, outputEncoding }`.
141
143
  The exec keys are off unless you turn them on: `execEnabled` defaults to
142
144
  `false`, `execHostIds` (host allow-list) starts empty, and
143
145
  `execWorkspaceIds` is an optional second layer where an empty list means
144
146
  "every workspace on an allowed host".
145
- - `exec-audit.jsonl` — one JSON line per `hosts.exec` attempt (accepted or
146
- refused): `{ ts, auditId, hostId, hostName, workspaceId, kind, command, cwd?,
147
+ - `exec-audit.jsonl` — one JSON line per `hosts.exec` attempt (accepted or refused): `{ ts, auditId, hostId, hostName, workspaceId, kind, command, cwd?,
147
148
  exitCode?, durationMs?, stdoutBytes?, stderrBytes?, truncated?, stdoutHead?,
148
149
  stderrHead?, refusal?, message? }`. Rotated to `exec-audit.jsonl.1` past 5 MB.
149
150
  `meta.info` returns its absolute path as `execAuditFile` so the settings page
150
151
  can open it.
151
- - `known_hosts.json` — trust-on-first-use host key fingerprints.
152
+ - `known_hosts.json` — trust-on-first-use host key fingerprints, readable through
153
+ `hosts.hostKeys` and prunable one authority at a time with `hosts.forgetHostKey`.
154
+ With `settings.hostKeyPolicy: "strict"` an unknown key is refused instead of
155
+ trusted (`409` `HOST_KEY_UNKNOWN`) — see the SSH trust section in the settings page.
152
156
  - `ssh-credentials.json` — `{ version, byHostId: { <hostId>: { password?, privateKey?, passphrase? } } }`,
153
157
  written by `hosts.credentials` with mode `0600`. Hosts listed in `~/.ssh/config`
154
158
  without an `IdentityFile` can be paired with a password here, so the plugin does
package/docs/VERIFY.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  Host code (lib/) reloads live with `plugin_manager set_plugin include:linked-workspace-ui`; client changes load with **应用 → 重新加载界面** (a full restart is only needed after re-installing the package). Then verify:
4
4
 
5
+ ## 主机密钥与输出编码(0.20.0)
6
+
7
+ 1. 设置 → 联动工作区 → 「SSH 主机密钥与输出编码」应能看到「主机密钥策略」(tofu / strict)、「远端命令输出编码」(utf8 / gbk),以及已记住的主机列表(每行显示 `host:port` 与 `SHA256:…` 指纹)。
8
+ 2. 把策略切到 strict,在「忘记」某个主机的密钥后再点该主机的工作区:目录树应报「Host key … is not known yet」,HTTP 409,且不会悄悄重新记住。
9
+ 3. 切回 tofu 再刷新:连接恢复,密钥重新出现在列表里。
10
+ 4. 把输出编码切到 gbk,用 `hosts.exec` 让中文 Windows 远端输出中文,应正常显示;切回 utf8 应变成乱码(说明不是被强行转码)。
11
+
5
12
  ## 本地改动推回远端(0.19.0)
6
13
 
7
14
  1. 在联动工作区的**本地**目录里改一个文件、新建一个文件,然后点目录栏的同步按钮:差异预览里能看到「新增 1 · 修改 1」,并列出这两个文件。
package/lib/client.js CHANGED
@@ -2527,6 +2527,19 @@ function attributeViolation(name, value, tagName) {
2527
2527
  autoPushExcludeLabel: '不要推送这些路径(每行一个,支持 *)',
2528
2528
  autoPushDebounceLabel: '停止编辑后等待(毫秒)',
2529
2529
  autoPushSaved: '自动推送设置已保存',
2530
+ sshTrustTitle: 'SSH 信任与编码',
2531
+ sshTrustHint: '默认信任第一次连接看到的主机密钥(TOFU);选「严格」后,没见过的主机一律拒绝。远端命令输出按下面的编码解码,中文 Windows 服务器常需要 GBK。',
2532
+ hostKeyPolicyLabel: '主机密钥策略',
2533
+ hostKeyPolicyTofu: '信任首次连接(TOFU)',
2534
+ hostKeyPolicyStrict: '只连接见过的主机(严格)',
2535
+ outputEncodingLabel: '远端命令输出编码',
2536
+ outputEncodingUtf8: 'UTF-8(大多数 Linux)',
2537
+ outputEncodingGbk: 'GBK(中文 Windows)',
2538
+ knownKeysTitle: '已知主机密钥',
2539
+ knownKeysEmpty: '还没有记录任何主机密钥。',
2540
+ forgetHostKey: '忘记',
2541
+ forgotHostKey: '已忘记 {{authority}} 的主机密钥',
2542
+ sshTrustSaved: 'SSH 设置已保存',
2530
2543
  execTitle: '远端命令执行',
2531
2544
  execHint: '默认关闭。开启后,会话里的模型可以通过 linked_workspace 的 exec 动作在远端跑命令;只对下面勾选的主机/工作区生效,每次尝试(含被拒)都记进审计日志。',
2532
2545
  execEnabledLabel: '允许在远端执行命令',
@@ -3051,6 +3064,19 @@ function attributeViolation(name, value, tagName) {
3051
3064
  autoPushExcludeLabel: 'Never push these paths (one per line, * allowed)',
3052
3065
  autoPushDebounceLabel: 'Wait after editing stops (ms)',
3053
3066
  autoPushSaved: 'Automatic push settings saved',
3067
+ sshTrustTitle: 'SSH trust and encodings',
3068
+ sshTrustHint: 'The first host key seen is trusted by default (TOFU); "strict" refuses a host we have never seen. Command output is decoded with the encoding below — Chinese Windows servers usually need GBK.',
3069
+ hostKeyPolicyLabel: 'Host key policy',
3070
+ hostKeyPolicyTofu: 'Trust the first key (TOFU)',
3071
+ hostKeyPolicyStrict: 'Only connect to known hosts (strict)',
3072
+ outputEncodingLabel: 'Remote command output encoding',
3073
+ outputEncodingUtf8: 'UTF-8 (most Linux hosts)',
3074
+ outputEncodingGbk: 'GBK (Chinese Windows)',
3075
+ knownKeysTitle: 'Known host keys',
3076
+ knownKeysEmpty: 'No host key recorded yet.',
3077
+ forgetHostKey: 'Forget',
3078
+ forgotHostKey: 'Forgot the host key for {{authority}}',
3079
+ sshTrustSaved: 'SSH settings saved',
3054
3080
  execTitle: 'Remote command execution',
3055
3081
  execHint: 'Off by default. When on, the model can run commands on the remote host through the linked_workspace "exec" action — only for the hosts and workspaces ticked below, and every attempt (refusals included) is audited.',
3056
3082
  execEnabledLabel: 'Allow running commands remotely',
@@ -3255,7 +3281,7 @@ function attributeViolation(name, value, tagName) {
3255
3281
  * Host methods the running DSH process does not have yet, the directory
3256
3282
  * pane says so instead of surfacing an unrelated error.
3257
3283
  */
3258
- var HOST_API_REVISION = 5;
3284
+ var HOST_API_REVISION = 6;
3259
3285
  var hostInfoProbe = null;
3260
3286
 
3261
3287
  function probeHostInfo() {
@@ -3739,6 +3765,11 @@ function attributeViolation(name, value, tagName) {
3739
3765
  '.rw-sync-tag{flex:none;min-width:52px;color:rgb(150,150,152)}',
3740
3766
  '.rw-sync-path{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:var(--dsw-font-mono,monospace)}',
3741
3767
  '.rw-autopush-list{width:100%;resize:vertical;font-family:var(--dsw-font-mono,monospace);font-size:12px}',
3768
+ '.rw-known-keys{display:flex;flex-direction:column;gap:6px;margin-top:8px}',
3769
+ '.rw-known-key{display:flex;align-items:center;gap:10px}',
3770
+ '.rw-known-key-main{flex:1 1 auto;min-width:0;display:flex;flex-direction:column;gap:2px}',
3771
+ '.rw-known-key-host{font-size:12px;color:var(--dsw-alias-text-2)}',
3772
+ '.rw-known-key-fp{font-size:11px;font-family:var(--dsw-font-mono,monospace);color:var(--dsw-alias-text-3);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
3742
3773
  '.rw-exec-item{display:flex;align-items:center;gap:8px;padding:7px 10px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-1);cursor:pointer;font-size:13px}',
3743
3774
  '.rw-exec-item input[type=checkbox]{margin:0;flex:none}',
3744
3775
  '.rw-exec-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
@@ -11094,6 +11125,140 @@ function rememberShowHidden(value) {
11094
11125
  return h('div', { className: 'rw-group' }, children);
11095
11126
  }
11096
11127
 
11128
+ /**
11129
+ * Host key trust and command-output encoding (0.20.0).
11130
+ *
11131
+ * Before this, a changed host key could only be cleared by hand-editing
11132
+ * `known_hosts.json`, and a Windows shell's GBK output arrived as mojibake.
11133
+ */
11134
+ function SshTrustSettingsGroup(props) {
11135
+ var t = props.t;
11136
+ var locale = props.locale;
11137
+ var localState = useState({ loading: true, saving: false, message: null });
11138
+ var local = localState[0];
11139
+ var setLocal = localState[1];
11140
+ var valuesState = useState({ hostKeyPolicy: 'tofu', outputEncoding: 'utf8' });
11141
+ var values = valuesState[0];
11142
+ var setValues = valuesState[1];
11143
+ var keysState = useState([]);
11144
+ var keys = keysState[0];
11145
+ var setKeys = keysState[1];
11146
+
11147
+ function refreshKeys() {
11148
+ apiCall('hosts.hostKeys', {}).then(function (result) {
11149
+ setKeys(Array.isArray(result.entries) ? result.entries : []);
11150
+ }).catch(function () {
11151
+ setKeys([]);
11152
+ });
11153
+ }
11154
+
11155
+ useEffect(function () {
11156
+ var alive = true;
11157
+ apiCall('settings.get', {}).then(function (settings) {
11158
+ if (!alive) return;
11159
+ setValues({
11160
+ hostKeyPolicy: settings.hostKeyPolicy === 'strict' ? 'strict' : 'tofu',
11161
+ outputEncoding: settings.outputEncoding === 'gbk' ? 'gbk' : 'utf8',
11162
+ });
11163
+ setLocal(function (previous) { return Object.assign({}, previous, { loading: false }); });
11164
+ }).catch(function () {
11165
+ if (alive) setLocal(function (previous) { return Object.assign({}, previous, { loading: false }); });
11166
+ });
11167
+ refreshKeys();
11168
+ return function () { alive = false; };
11169
+ }, []);
11170
+
11171
+ function save(patch, okText) {
11172
+ setLocal(function (previous) { return Object.assign({}, previous, { saving: true, message: null }); });
11173
+ apiCall('settings.update', patch).then(function (settings) {
11174
+ setValues({
11175
+ hostKeyPolicy: settings.hostKeyPolicy === 'strict' ? 'strict' : 'tofu',
11176
+ outputEncoding: settings.outputEncoding === 'gbk' ? 'gbk' : 'utf8',
11177
+ });
11178
+ setLocal({ loading: false, saving: false, message: { kind: 'success', text: okText } });
11179
+ }).catch(function (error) {
11180
+ setLocal({ loading: false, saving: false, message: { kind: 'error', text: messageOf(error, t, locale) } });
11181
+ });
11182
+ }
11183
+
11184
+ function forget(entry) {
11185
+ var params = entry.hostId ? { hostId: entry.hostId } : { authority: entry.authority };
11186
+ setLocal(function (previous) { return Object.assign({}, previous, { saving: true, message: null }); });
11187
+ apiCall('hosts.forgetHostKey', params).then(function () {
11188
+ setLocal({
11189
+ loading: false,
11190
+ saving: false,
11191
+ message: { kind: 'success', text: t('forgotHostKey', { authority: entry.authority }) },
11192
+ });
11193
+ refreshKeys();
11194
+ }).catch(function (error) {
11195
+ setLocal({ loading: false, saving: false, message: { kind: 'error', text: messageOf(error, t, locale) } });
11196
+ });
11197
+ }
11198
+
11199
+ var children = [
11200
+ h('div', { className: 'rw-group-head' },
11201
+ h('span', { className: 'rw-group-title' }, t('sshTrustTitle')),
11202
+ local.saving ? Spinner(12) : null),
11203
+ h('div', { className: 'rw-group-hint' }, t('sshTrustHint')),
11204
+ h('div', { className: 'rw-inline', style: { marginTop: 10, flexWrap: 'wrap', gap: 12 } },
11205
+ h('span', { className: 'rw-setting-label' }, t('hostKeyPolicyLabel')),
11206
+ h('select', {
11207
+ className: 'rw-input',
11208
+ value: values.hostKeyPolicy,
11209
+ onChange: function (event) {
11210
+ var next = event.currentTarget.value;
11211
+ setValues(function (previous) { return Object.assign({}, previous, { hostKeyPolicy: next }); });
11212
+ save({ hostKeyPolicy: next }, t('sshTrustSaved'));
11213
+ },
11214
+ },
11215
+ h('option', { value: 'tofu' }, t('hostKeyPolicyTofu')),
11216
+ h('option', { value: 'strict' }, t('hostKeyPolicyStrict')))),
11217
+ h('div', { className: 'rw-inline', style: { marginTop: 10, flexWrap: 'wrap', gap: 12 } },
11218
+ h('span', { className: 'rw-setting-label' }, t('outputEncodingLabel')),
11219
+ h('select', {
11220
+ className: 'rw-input',
11221
+ value: values.outputEncoding,
11222
+ onChange: function (event) {
11223
+ var next = event.currentTarget.value;
11224
+ setValues(function (previous) { return Object.assign({}, previous, { outputEncoding: next }); });
11225
+ save({ outputEncoding: next }, t('sshTrustSaved'));
11226
+ },
11227
+ },
11228
+ h('option', { value: 'utf8' }, t('outputEncodingUtf8')),
11229
+ h('option', { value: 'gbk' }, t('outputEncodingGbk')))),
11230
+ h('div', { className: 'rw-group-head', style: { marginTop: 14 } },
11231
+ h('span', { className: 'rw-group-title' }, t('knownKeysTitle'))),
11232
+ ];
11233
+
11234
+ if (keys.length === 0) {
11235
+ children.push(h('div', { className: 'rw-group-hint' }, t('knownKeysEmpty')));
11236
+ } else {
11237
+ children.push(h('div', { className: 'rw-known-keys' }, keys.map(function (entry) {
11238
+ return h('div', { className: 'rw-known-key', key: entry.authority },
11239
+ h('div', { className: 'rw-known-key-main' },
11240
+ h('span', { className: 'rw-known-key-host' }, entry.hostName ? entry.hostName + ' · ' + entry.authority : entry.authority),
11241
+ h('span', { className: 'rw-known-key-fp', title: entry.fingerprint }, entry.fingerprint)),
11242
+ h('button', {
11243
+ type: 'button',
11244
+ className: 'rw-btn rw-btn-sm',
11245
+ onClick: function () { forget(entry); },
11246
+ }, t('forgetHostKey')));
11247
+ })));
11248
+ }
11249
+
11250
+ if (local.message) {
11251
+ children.push(h(Banner, {
11252
+ kind: local.message.kind === 'success' ? 'success' : 'error',
11253
+ onClose: function () {
11254
+ setLocal(function (previous) { return Object.assign({}, previous, { message: null }); });
11255
+ },
11256
+ }, local.message.text));
11257
+ }
11258
+
11259
+ return h('div', { className: 'rw-group' }, children);
11260
+ }
11261
+
11097
11262
  function ConnectionsPage(props) {
11098
11263
  var ctx = props.ctx;
11099
11264
  var locale = useLocale(ctx);
@@ -11161,6 +11326,7 @@ function rememberShowHidden(value) {
11161
11326
  workspaces: links.concat(remotes),
11162
11327
  }),
11163
11328
  h(AutoPushSettingsGroup, { t: t, locale: locale }),
11329
+ h(SshTrustSettingsGroup, { t: t, locale: locale }),
11164
11330
  adding === 'linked'
11165
11331
  ? h(AddWorkspaceFlow, {
11166
11332
  ctx: ctx, t: t, locale: locale,
package/lib/index.js CHANGED
@@ -22,7 +22,7 @@ import { appendFile, mkdir, readdir, rename, rm, stat as fsStat } from 'node:fs/
22
22
  import { homedir, tmpdir } from 'node:os'
23
23
  import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep } from 'node:path'
24
24
  import { fileURLToPath } from 'node:url'
25
- import { listHosts, RemoteHost, SshError, writeLocalCredential } from './ssh.js'
25
+ import { forgetKnownHost, listHosts, listKnownHosts, RemoteHost, SshError, writeLocalCredential } from './ssh.js'
26
26
  import * as linkedFs from './linked.js'
27
27
  import * as git from './git.js'
28
28
 
@@ -38,7 +38,7 @@ export const inject = ['webServer', 'tools', 'systemPrompt', 'workingDirectory']
38
38
  * is still running an older copy of the Host — refreshing the page only swaps
39
39
  * the browser bundle, so the two halves can drift by one restart.
40
40
  */
41
- const API_REVISION = 5
41
+ const API_REVISION = 6
42
42
 
43
43
  /** When this copy of the Host was loaded; shown by `meta.info`. */
44
44
  const STARTED_AT = new Date().toISOString()
@@ -55,9 +55,13 @@ const PACKAGE_VERSION = (() => {
55
55
 
56
56
  const DATA_VERSION = 1
57
57
  const SETTINGS_VERSION = 1
58
- const SETTINGS_DEFAULTS = Object.freeze({ editorTheme: 'github-light', editorThemeFamily: 'github', editorThemeMode: 'system', fileOpenMode: 'editor', autoSave: false, execEnabled: false, execTimeoutMs: 60000, execMaxOutputChars: 200000, execShell: '', autoPushEnabled: false, autoPushDebounceMs: 1500 })
58
+ const SETTINGS_DEFAULTS = Object.freeze({ editorTheme: 'github-light', editorThemeFamily: 'github', editorThemeMode: 'system', fileOpenMode: 'editor', autoSave: false, execEnabled: false, execTimeoutMs: 60000, execMaxOutputChars: 200000, execShell: '', autoPushEnabled: false, autoPushDebounceMs: 1500, hostKeyPolicy: 'tofu', outputEncoding: 'utf8' })
59
59
  const AUTO_PUSH_DEBOUNCE_MIN = 300
60
60
  const AUTO_PUSH_DEBOUNCE_MAX = 60000
61
+ /** `tofu` trusts a new host key once; `strict` refuses one it has never seen. */
62
+ const HOST_KEY_POLICIES = new Set(['tofu', 'strict'])
63
+ /** Command output encoding: `utf8` for POSIX hosts, `gbk` for Chinese Windows. */
64
+ const OUTPUT_ENCODINGS = new Set(['utf8', 'gbk'])
61
65
  /** Exec allow-lists travel as arrays, so they are not part of the frozen defaults. */
62
66
  const EMPTY_ID_LIST = Object.freeze([])
63
67
  const EDITOR_THEME_FAMILIES = new Set(['github', 'solarized', 'one', 'dracula', 'monokai', 'nord', 'vscode', 'xcode', 'catppuccin'])
@@ -163,6 +167,7 @@ const ERROR_STATUS = {
163
167
  SSH_CONNECT: 502,
164
168
  AUTH_FAILED: 401,
165
169
  HOST_KEY_MISMATCH: 409,
170
+ HOST_KEY_UNKNOWN: 409,
166
171
  TIMEOUT: 408,
167
172
  FS_NOT_FOUND: 404,
168
173
  FS_PERMISSION: 403,
@@ -509,6 +514,12 @@ class SettingsStore {
509
514
  this.value.autoPushInclude = normalizeStringList(settings.autoPushInclude)
510
515
  this.value.autoPushExclude = normalizeStringList(settings.autoPushExclude)
511
516
  }
517
+ if (settings && typeof settings === 'object' && HOST_KEY_POLICIES.has(settings.hostKeyPolicy)) {
518
+ this.value.hostKeyPolicy = settings.hostKeyPolicy
519
+ }
520
+ if (settings && typeof settings === 'object' && OUTPUT_ENCODINGS.has(settings.outputEncoding)) {
521
+ this.value.outputEncoding = settings.outputEncoding
522
+ }
512
523
  if (settings && typeof settings === 'object' && settings.themeExplicit === true) {
513
524
  this.themeExplicit = true
514
525
  }
@@ -571,6 +582,14 @@ class SettingsStore {
571
582
  if (typeof patch.autoSave !== 'boolean') throw new ApiError('BAD_REQUEST', '自动保存设置无效')
572
583
  this.value.autoSave = patch.autoSave
573
584
  }
585
+ if (patch && typeof patch === 'object' && patch.hostKeyPolicy !== undefined) {
586
+ if (!HOST_KEY_POLICIES.has(patch.hostKeyPolicy)) throw new ApiError('BAD_REQUEST', '主机密钥策略无效')
587
+ this.value.hostKeyPolicy = patch.hostKeyPolicy
588
+ }
589
+ if (patch && typeof patch === 'object' && patch.outputEncoding !== undefined) {
590
+ if (!OUTPUT_ENCODINGS.has(patch.outputEncoding)) throw new ApiError('BAD_REQUEST', '输出编码无效')
591
+ this.value.outputEncoding = patch.outputEncoding
592
+ }
574
593
  if (patch && typeof patch === 'object' && patch.execEnabled !== undefined) {
575
594
  if (typeof patch.execEnabled !== 'boolean') throw new ApiError('BAD_REQUEST', '远端命令执行设置无效')
576
595
  this.value.execEnabled = patch.execEnabled
@@ -910,11 +929,14 @@ function linkedManifestFor(record) {
910
929
  // ── connection pool ─────────────────────────────────────────────────────────
911
930
 
912
931
  class HostPool {
913
- constructor({ knownHostsFile, credentialFile }) {
932
+ constructor({ knownHostsFile, credentialFile, hostKeyPolicy }) {
914
933
  this.knownHostsFile = knownHostsFile
915
934
  // Secrets the user stored from the add-workspace dialog. Kept apart from the
916
935
  // SSH Manager so the plugin works without `dsh-ssh-tunnel`.
917
936
  this.credentialFile = credentialFile || null
937
+ // Function or literal, forwarded to every RemoteHost so the trust policy is
938
+ // decided at connect time rather than at plugin load.
939
+ this.hostKeyPolicy = hostKeyPolicy || 'tofu'
918
940
  this.records = new Map() // hostId -> HostRecord
919
941
  this.connections = new Map() // hostId -> { authority, remote: RemoteHost }
920
942
  this.connecting = new Map() // hostId -> { authority, promise }
@@ -1009,6 +1031,7 @@ class HostPool {
1009
1031
  host: hostRecord,
1010
1032
  knownHostsFile: this.knownHostsFile,
1011
1033
  credentialFile: this.credentialFile,
1034
+ hostKeyPolicy: this.hostKeyPolicy,
1012
1035
  connectTimeoutMs: CONNECT_TIMEOUT_MS,
1013
1036
  logger: log,
1014
1037
  onLost: (info) => this.noteConnectionLost(hostRecord.id, remote, info && info.reason),
@@ -1074,6 +1097,8 @@ export function apply(ctx) {
1074
1097
  const pool = new HostPool({
1075
1098
  knownHostsFile: join(dir, 'known_hosts.json'),
1076
1099
  credentialFile: join(dir, 'ssh-credentials.json'),
1100
+ // Read on every connection: the user can switch the policy while running.
1101
+ hostKeyPolicy: () => settingsStore.get().hostKeyPolicy,
1077
1102
  })
1078
1103
 
1079
1104
  let hostsCache = null
@@ -3032,6 +3057,64 @@ export function apply(ctx) {
3032
3057
 
3033
3058
  // Free space on the volume that holds a remote path (F2). `df -Pk` is the
3034
3059
  // portable form: one line of numbers in 1K blocks.
3060
+ /**
3061
+ * Every remembered host key, so a changed one can be forgotten in the UI
3062
+ * instead of hand-editing `known_hosts.json` (0.20.0).
3063
+ */
3064
+ async 'hosts.hostKeys'() {
3065
+ const entries = await listKnownHosts(join(dir, 'known_hosts.json'))
3066
+ let hosts = []
3067
+ try {
3068
+ hosts = await refreshHosts()
3069
+ } catch {
3070
+ hosts = []
3071
+ }
3072
+ const byAuthority = new Map()
3073
+ for (const host of hosts) {
3074
+ const authority = `${host.host}:${host.port === 22 ? 22 : host.port}`
3075
+ byAuthority.set(authority, { hostId: host.id, hostName: host.name || host.host })
3076
+ }
3077
+ return {
3078
+ entries: entries.map((entry) => {
3079
+ const owner = byAuthority.get(entry.authority) || {}
3080
+ return {
3081
+ authority: entry.authority,
3082
+ fingerprint: entry.fingerprint,
3083
+ firstSeen: entry.firstSeen,
3084
+ hostId: owner.hostId || '',
3085
+ hostName: owner.hostName || '',
3086
+ }
3087
+ }),
3088
+ }
3089
+ },
3090
+
3091
+ /**
3092
+ * Drop the remembered host key for one host. The next connection goes back
3093
+ * to a first-use decision (or a refusal while the policy is `strict`).
3094
+ */
3095
+ async 'hosts.forgetHostKey'(params = {}) {
3096
+ const requestedAuthority = typeof params.authority === 'string' && params.authority.trim() !== ''
3097
+ ? params.authority.trim()
3098
+ : '';
3099
+ let host = null;
3100
+ if (typeof params.hostId === 'string' && params.hostId.trim() !== '') {
3101
+ host = await findHost(params.hostId.trim());
3102
+ } else if (!requestedAuthority) {
3103
+ throw new ApiError('BAD_REQUEST', 'hostId 或 authority 必须提供一个');
3104
+ }
3105
+ const authority = requestedAuthority || `${host.host}:${host.port}`;
3106
+ if (host) {
3107
+ const connection = pool.connections.get(host.id);
3108
+ if (connection) {
3109
+ pool.connections.delete(host.id);
3110
+ await connection.remote.dispose().catch(() => {});
3111
+ }
3112
+ }
3113
+ const removed = await forgetKnownHost(join(dir, 'known_hosts.json'), authority);
3114
+ if (removed) log('info', `forgot the host key for ${authority}`);
3115
+ return { authority, removed };
3116
+ },
3117
+
3035
3118
  async 'hosts.df'(params = {}) {
3036
3119
  const host = await findHost(params.hostId)
3037
3120
  const remote = await connectHost(host)
@@ -3131,7 +3214,7 @@ export function apply(ctx) {
3131
3214
  let result
3132
3215
  try {
3133
3216
  const remote = scope ? scope.remote : await connectHost(host)
3134
- result = await remote.exec(wrapped, { timeoutMs })
3217
+ result = await remote.exec(wrapped, { timeoutMs, encoding: settings.outputEncoding })
3135
3218
  } catch (error) {
3136
3219
  const durationMs = Date.now() - started
3137
3220
  const timedOut = error && error.code === 'TIMEOUT'
package/lib/ssh.js CHANGED
@@ -57,11 +57,29 @@ const STATUS_BY_CODE = Object.freeze({
57
57
  FS_NOT_FOUND: 404,
58
58
  TIMEOUT: 408,
59
59
  HOST_KEY_MISMATCH: 409,
60
+ HOST_KEY_UNKNOWN: 409,
60
61
  FS_IS_DIR: 409,
61
62
  FS_NOT_DIR: 409,
62
63
  INTERNAL: 500,
63
64
  });
64
65
 
66
+ /**
67
+ * Decode a command's output with the encoding the remote host actually uses.
68
+ *
69
+ * Most servers speak UTF-8, but a Windows OpenSSH session (or a shell with a
70
+ * legacy code page) answers in GBK, which arrives as mojibake under UTF-8.
71
+ * `TextDecoder` handles both without pulling in another dependency.
72
+ */
73
+ export function decodeOutput(bundle, encoding = 'utf8') {
74
+ const buffer = Buffer.isBuffer(bundle) ? bundle : Buffer.from(bundle === undefined || bundle === null ? '' : String(bundle), 'utf8');
75
+ if (encoding !== 'gbk') return buffer.toString('utf8');
76
+ try {
77
+ return new TextDecoder('gbk').decode(buffer);
78
+ } catch {
79
+ return buffer.toString('utf8');
80
+ }
81
+ }
82
+
65
83
  /** Raw error codes that mean "the connection is gone", not "the operation failed". */
66
84
  const CONNECTION_ERROR_CODES = new Set([
67
85
  'ECONNRESET',
@@ -868,6 +886,43 @@ async function readKnownHostsStore(file) {
868
886
  return { version: KNOWN_HOSTS_VERSION, byAuthority };
869
887
  }
870
888
 
889
+ /**
890
+ * Read every remembered host key, with the authorities a user can act on.
891
+ *
892
+ * The plugin shows these in settings so a changed key can be forgotten without
893
+ * hand-editing `known_hosts.json`.
894
+ */
895
+ export async function listKnownHosts(file) {
896
+ const store = await readKnownHostsStore(file);
897
+ return Object.keys(store.byAuthority)
898
+ .sort()
899
+ .map((authority) => ({
900
+ authority,
901
+ fingerprint: store.byAuthority[authority].fingerprint,
902
+ firstSeen: store.byAuthority[authority].firstSeen || 0,
903
+ }));
904
+ }
905
+
906
+ /**
907
+ * Forget the remembered key for one authority.
908
+ *
909
+ * Returns true when an entry was removed. The next connection is then a normal
910
+ * trust-on-first-use decision again (or a refusal while the policy is strict).
911
+ */
912
+ export async function forgetKnownHost(file, authority) {
913
+ const wanted = String(authority || '').trim();
914
+ if (!wanted) throw new SshError('BAD_REQUEST', '需要提供 authority(host:port)');
915
+ let removed = false;
916
+ await withFileLock(file, async () => {
917
+ const store = await readKnownHostsStore(file);
918
+ if (!store.byAuthority[wanted]) return;
919
+ delete store.byAuthority[wanted];
920
+ await writeKnownHostsStore(file, store);
921
+ removed = true;
922
+ });
923
+ return removed;
924
+ }
925
+
871
926
  async function writeKnownHostsStore(file, store) {
872
927
  const dir = path.dirname(file);
873
928
  await fs.mkdir(dir, { recursive: true });
@@ -915,6 +970,7 @@ export class RemoteHost {
915
970
  #sftpCreating = null;
916
971
  #homeDir = null;
917
972
  #hostKeyMismatch = null;
973
+ #hostKeyUnknown = null;
918
974
  #generation = 0;
919
975
  #logger;
920
976
  #dataDir;
@@ -933,7 +989,7 @@ export class RemoteHost {
933
989
  * }} options
934
990
  */
935
991
  constructor(options = {}) {
936
- const { host, knownHostsFile, connectTimeoutMs, logger, dataDir, credentialFile, onLost } = options || {};
992
+ const { host, knownHostsFile, connectTimeoutMs, logger, dataDir, credentialFile, onLost, hostKeyPolicy } = options || {};
937
993
  if (!isPlainObject(host) || !asString(host.host).trim()) {
938
994
  throw new SshError('INTERNAL', 'RemoteHost requires a host record with a non-empty "host" field');
939
995
  }
@@ -949,6 +1005,7 @@ export class RemoteHost {
949
1005
 
950
1006
  this.host = hostRecord;
951
1007
  this.knownHostsFile = knownHostsFile;
1008
+ this.hostKeyPolicy = typeof hostKeyPolicy === 'function' || typeof hostKeyPolicy === 'string' ? hostKeyPolicy : 'tofu';
952
1009
  const timeout = Number(connectTimeoutMs);
953
1010
  this.connectTimeoutMs = Number.isFinite(timeout) && timeout > 0 ? timeout : DEFAULT_CONNECT_TIMEOUT_MS;
954
1011
  this.#logger = typeof logger === 'function' ? logger : null;
@@ -1010,6 +1067,7 @@ export class RemoteHost {
1010
1067
  const auth = await this.#resolveAuth();
1011
1068
  const knownHosts = await readKnownHostsStore(this.knownHostsFile);
1012
1069
  this.#hostKeyMismatch = null;
1070
+ this.#hostKeyUnknown = null;
1013
1071
 
1014
1072
  const client = new ssh2.Client();
1015
1073
  this.#generation += 1;
@@ -1135,23 +1193,42 @@ export class RemoteHost {
1135
1193
  }
1136
1194
 
1137
1195
  #classifyConnectError(raw) {
1138
- if (raw instanceof SshError) return raw;
1139
- const message = String((raw && raw.message) || raw || 'connection failed');
1140
- const level = raw && raw.level;
1141
- const code = raw && raw.code;
1142
- const mismatch = this.#hostKeyMismatch;
1143
-
1144
- if (mismatch && (/host denied/i.test(message) || /verification failed/i.test(message) || level === 'handshake')) {
1196
+ const earlyMessage = String((raw && raw.message) || raw || 'connection failed');
1197
+ const earlyLevel = raw && raw.level;
1198
+ // The host-key refusals must be recognised before the "already an SshError"
1199
+ // shortcut below: ssh2 reports the denial as a handshake error, which the
1200
+ // SFTP/exec layer has usually converted into a generic INTERNAL SshError by
1201
+ // the time it reaches us. Our own flag is the authoritative signal.
1202
+ const hostKeyRefusal = raw instanceof SshError
1203
+ || /host denied/i.test(earlyMessage)
1204
+ || /verification failed/i.test(earlyMessage)
1205
+ || earlyLevel === 'handshake';
1206
+ if (this.#hostKeyUnknown && hostKeyRefusal) {
1207
+ return new SshError(
1208
+ 'HOST_KEY_UNKNOWN',
1209
+ [
1210
+ `Host key for ${this.authority} is not known yet and the policy is "strict":`,
1211
+ `the server presented ${this.#hostKeyUnknown.actual}.`,
1212
+ `Either switch the host key policy back to "tofu" or trust this key on purpose.`,
1213
+ ].join(' '),
1214
+ { cause: raw },
1215
+ );
1216
+ }
1217
+ if (this.#hostKeyMismatch && hostKeyRefusal) {
1145
1218
  return new SshError(
1146
1219
  'HOST_KEY_MISMATCH',
1147
1220
  [
1148
1221
  `Host key mismatch for ${this.authority}:`,
1149
- `expected ${mismatch.expected} but the server presented ${mismatch.actual}.`,
1150
- `If this change is expected, remove the entry for ${this.authority} from ${this.knownHostsFile} and reconnect.`,
1222
+ `expected ${this.#hostKeyMismatch.expected} but the server presented ${this.#hostKeyMismatch.actual}.`,
1223
+ `If this change is expected, forget the stored key in Settings → Linked workspaces and reconnect.`,
1151
1224
  ].join(' '),
1152
1225
  { cause: raw },
1153
1226
  );
1154
1227
  }
1228
+ if (raw instanceof SshError) return raw;
1229
+ const message = earlyMessage;
1230
+ const level = earlyLevel;
1231
+ const code = raw && raw.code;
1155
1232
  if (
1156
1233
  /all configured authentication methods failed/i.test(message) ||
1157
1234
  /cannot parse privatekey/i.test(message) ||
@@ -1271,6 +1348,12 @@ export class RemoteHost {
1271
1348
 
1272
1349
  // -- host key trust -------------------------------------------------------
1273
1350
 
1351
+ /** The policy can change while the plugin runs, so it is read every time. */
1352
+ #hostKeyPolicy() {
1353
+ const value = typeof this.hostKeyPolicy === 'function' ? this.hostKeyPolicy() : this.hostKeyPolicy;
1354
+ return value === 'strict' ? 'strict' : 'tofu';
1355
+ }
1356
+
1274
1357
  #verifyHostKey(store, hashedKey, callback) {
1275
1358
  let answered = false;
1276
1359
  const answer = (permitted) => {
@@ -1283,6 +1366,15 @@ export class RemoteHost {
1283
1366
  const entry = store.byAuthority[this.authority];
1284
1367
 
1285
1368
  if (!entry) {
1369
+ // `strict` refuses anything we have not seen before, so a man-in-the-middle
1370
+ // cannot win the first connection either. The default (`tofu`) keeps the
1371
+ // usual behaviour of trusting the first key and remembering it.
1372
+ if (this.#hostKeyPolicy() === 'strict') {
1373
+ this.#hostKeyUnknown = { actual: fingerprint };
1374
+ this.#log('error', `Refusing unknown host key for ${this.authority} (policy: strict): ${fingerprint}`);
1375
+ answer(false);
1376
+ return;
1377
+ }
1286
1378
  this.#log('info', `Trusting new host key for ${this.authority}: ${fingerprint}`);
1287
1379
  this.#rememberHostKey(fingerprint).then(
1288
1380
  () => answer(true),
@@ -1426,6 +1518,7 @@ export class RemoteHost {
1426
1518
  const requestedTimeout = Number(opts.timeoutMs);
1427
1519
  const timeoutMs = Number.isFinite(requestedTimeout) && requestedTimeout > 0 ? Math.floor(requestedTimeout) : defaultTimeoutMs;
1428
1520
  const signal = opts.signal && typeof opts.signal.addEventListener === 'function' ? opts.signal : null;
1521
+ const encoding = opts.encoding === 'gbk' ? 'gbk' : 'utf8';
1429
1522
  const shortCommand = commandText.length > 120 ? `${commandText.slice(0, 117)}...` : commandText;
1430
1523
  const label = `exec ${JSON.stringify(shortCommand)}`;
1431
1524
 
@@ -1530,8 +1623,8 @@ export class RemoteHost {
1530
1623
  channel.on('error', (streamErr) => settle(streamErr));
1531
1624
  channel.on('close', (code) => {
1532
1625
  settle(null, {
1533
- stdout: Buffer.concat(stdout).toString('utf8'),
1534
- stderr: Buffer.concat(stderr).toString('utf8'),
1626
+ stdout: decodeOutput(Buffer.concat(stdout), encoding),
1627
+ stderr: decodeOutput(Buffer.concat(stderr), encoding),
1535
1628
  code: typeof code === 'number' ? code : 0,
1536
1629
  });
1537
1630
  });
@@ -1560,7 +1653,7 @@ export class RemoteHost {
1560
1653
  }
1561
1654
  }
1562
1655
 
1563
- async #exec(command) {
1656
+ async #exec(command, encoding = 'utf8') {
1564
1657
  return this.#retry(`exec ${JSON.stringify(command)}`, async () => {
1565
1658
  const client = await this.#readyClient();
1566
1659
  return new Promise((resolve, reject) => {
@@ -1586,8 +1679,8 @@ export class RemoteHost {
1586
1679
  finish(null, {
1587
1680
  code: typeof code === 'number' ? code : 0,
1588
1681
  signal: signal || null,
1589
- stdout: Buffer.concat(stdout).toString('utf8'),
1590
- stderr: Buffer.concat(stderr).toString('utf8'),
1682
+ stdout: decodeOutput(Buffer.concat(stdout), encoding),
1683
+ stderr: decodeOutput(Buffer.concat(stderr), encoding),
1591
1684
  });
1592
1685
  });
1593
1686
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-linked-workspace",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Linked local ⇄ remote workspaces and remote workspaces for DeepSeek Harness: theme-aware split editor, file-type icons, and agent tools that edit remote files directly.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",