dsh-linked-workspace 0.19.0 → 0.20.1

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,18 @@
2
2
 
3
3
  English · [简体中文](CHANGELOG.zh.md)
4
4
 
5
+ ## 0.20.1 — 2026-11-19
6
+
7
+ - **Overlays now live in the browser top layer.** The add-workspace dialog, every confirm/prompt dialog and the welcome card render into a `<dialog>` element with `showModal()`, so no neighbouring column (the right pane or the chat composer) can cover them. The old `z-index` values only worked inside one stacking context, which is why the same dialog was sometimes clipped.
8
+ - Esc still closes these overlays, and it now hangs off the top-layer host itself: cancelling goes through React, so the overlay is removed from the DOM instead of leaving a closed dialog behind.
9
+
10
+ ## 0.20.0 — 2026-11-19
11
+
12
+ - **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).
13
+ - **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.
14
+ - **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).
15
+ - `HOST_KEY_UNKNOWN` (409): a strict refusal now has its own error code and message instead of a generic `INTERNAL`.
16
+ - `apiRevision` 5 → 6.
5
17
  ## 0.19.0 — 2026-11-19
6
18
 
7
19
  - **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」,并列出这两个文件。
@@ -308,6 +315,8 @@ Host code (lib/) reloads live with `plugin_manager set_plugin include:linked-wor
308
315
  16. 触发一次错误提示后,再打开一个文件或点「刷新目录」:之前那条红色提示自动消失。
309
316
  17. 传一个较大的目录到远端,观察队列对话框的进行中行:进度后面会跟上吞吐,形如 `已传 3 个 · 12.0 MB · 4.1 MB/s`。
310
317
  18. 右键工作区根节点:菜单里**没有**「更改权限」(也没有「重命名」「删除」「移动到…」)。绕过界面直接请求 `fs.chmod` 并把 `path` 指向工作区远端根:返回 400「不能修改工作区根目录的权限」,随后 `fs.stat` 的权限保持不变。
318
+ 19. **覆盖层置顶(0.20.1)**:打开「添加工作区」弹窗时,右侧目录树与对话输入框都应变暗且完全在弹窗之下(在输入框位置 `document.elementFromPoint` 应命中遮罩);弹窗宿主是 `document.body` 下 `showModal()` 打开的 `<dialog class="rw-top-layer">`。按 Esc:弹窗消失且 `.rw-top-layer` 数量归 0(不能留下已关闭的 dialog),随后再点「添加工作区」仍能重新打开。
319
+ 20. **其它覆盖层(0.20.1)**:右键「移动到…」等确认对话框与首次运行欢迎卡片同样走 `.rw-top-layer`;Esc、点遮罩、点关闭按钮三种方式都能把宿主一起移除。
311
320
  ## 旧 Host 自检(0.15.0)
312
321
 
313
322
  1. **正常时不打扰**:插件已重启过后打开任意目录树,顶部**不应**出现任何黄色提示条。
package/lib/client.js CHANGED
@@ -26,6 +26,10 @@ window.__ModuleLoader__.load({
26
26
  'use strict';
27
27
 
28
28
  var React = require('react');
29
+ // react-dom is optional: some hosts expose it, some do not. It is only needed
30
+ // to portal overlays out of the plugin's slot subtree (see PortalBackdrop).
31
+ var reactDom = null;
32
+ try { reactDom = require('react-dom'); } catch (error) { reactDom = null; }
29
33
  var h = React.createElement;
30
34
  var useState = React.useState;
31
35
  var useEffect = React.useEffect;
@@ -2527,6 +2531,19 @@ function attributeViolation(name, value, tagName) {
2527
2531
  autoPushExcludeLabel: '不要推送这些路径(每行一个,支持 *)',
2528
2532
  autoPushDebounceLabel: '停止编辑后等待(毫秒)',
2529
2533
  autoPushSaved: '自动推送设置已保存',
2534
+ sshTrustTitle: 'SSH 信任与编码',
2535
+ sshTrustHint: '默认信任第一次连接看到的主机密钥(TOFU);选「严格」后,没见过的主机一律拒绝。远端命令输出按下面的编码解码,中文 Windows 服务器常需要 GBK。',
2536
+ hostKeyPolicyLabel: '主机密钥策略',
2537
+ hostKeyPolicyTofu: '信任首次连接(TOFU)',
2538
+ hostKeyPolicyStrict: '只连接见过的主机(严格)',
2539
+ outputEncodingLabel: '远端命令输出编码',
2540
+ outputEncodingUtf8: 'UTF-8(大多数 Linux)',
2541
+ outputEncodingGbk: 'GBK(中文 Windows)',
2542
+ knownKeysTitle: '已知主机密钥',
2543
+ knownKeysEmpty: '还没有记录任何主机密钥。',
2544
+ forgetHostKey: '忘记',
2545
+ forgotHostKey: '已忘记 {{authority}} 的主机密钥',
2546
+ sshTrustSaved: 'SSH 设置已保存',
2530
2547
  execTitle: '远端命令执行',
2531
2548
  execHint: '默认关闭。开启后,会话里的模型可以通过 linked_workspace 的 exec 动作在远端跑命令;只对下面勾选的主机/工作区生效,每次尝试(含被拒)都记进审计日志。',
2532
2549
  execEnabledLabel: '允许在远端执行命令',
@@ -3051,6 +3068,19 @@ function attributeViolation(name, value, tagName) {
3051
3068
  autoPushExcludeLabel: 'Never push these paths (one per line, * allowed)',
3052
3069
  autoPushDebounceLabel: 'Wait after editing stops (ms)',
3053
3070
  autoPushSaved: 'Automatic push settings saved',
3071
+ sshTrustTitle: 'SSH trust and encodings',
3072
+ 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.',
3073
+ hostKeyPolicyLabel: 'Host key policy',
3074
+ hostKeyPolicyTofu: 'Trust the first key (TOFU)',
3075
+ hostKeyPolicyStrict: 'Only connect to known hosts (strict)',
3076
+ outputEncodingLabel: 'Remote command output encoding',
3077
+ outputEncodingUtf8: 'UTF-8 (most Linux hosts)',
3078
+ outputEncodingGbk: 'GBK (Chinese Windows)',
3079
+ knownKeysTitle: 'Known host keys',
3080
+ knownKeysEmpty: 'No host key recorded yet.',
3081
+ forgetHostKey: 'Forget',
3082
+ forgotHostKey: 'Forgot the host key for {{authority}}',
3083
+ sshTrustSaved: 'SSH settings saved',
3054
3084
  execTitle: 'Remote command execution',
3055
3085
  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
3086
  execEnabledLabel: 'Allow running commands remotely',
@@ -3255,7 +3285,7 @@ function attributeViolation(name, value, tagName) {
3255
3285
  * Host methods the running DSH process does not have yet, the directory
3256
3286
  * pane says so instead of surfacing an unrelated error.
3257
3287
  */
3258
- var HOST_API_REVISION = 5;
3288
+ var HOST_API_REVISION = 6;
3259
3289
  var hostInfoProbe = null;
3260
3290
 
3261
3291
  function probeHostInfo() {
@@ -3721,6 +3751,8 @@ function attributeViolation(name, value, tagName) {
3721
3751
  '.rw-tabs{display:flex;gap:4px;padding:3px;border-radius:9px;background:var(--dsw-alias-bg-layer-1);border:1px solid var(--dsw-alias-border-l1)}',
3722
3752
  '.rw-tab{flex:1 1 auto;height:28px;display:inline-flex;align-items:center;justify-content:center;gap:6px;border:0;border-radius:7px;background:transparent;font:inherit;font-size:12px;color:var(--dsw-alias-label-secondary);cursor:pointer}',
3723
3753
  '.rw-tab.is-on{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);font-weight:600;box-shadow:0 0 0 1px var(--dsw-alias-border-l1)}',
3754
+ '.rw-top-layer{position:fixed;inset:0;width:100%;height:100%;max-width:none;max-height:none;margin:0;padding:0;border:0;background:transparent;overflow:visible;color:inherit}',
3755
+ '.rw-top-layer::backdrop{background:transparent}',
3724
3756
  '.rw-modal-backdrop{position:fixed;inset:0;z-index:1200;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(0,0,0,.34)}',
3725
3757
  '.rw-modal{display:flex;flex-direction:column;width:min(620px,100%);max-height:min(760px,88vh);border:1px solid var(--dsw-alias-border-l2);border-radius:16px;background:var(--dsw-alias-bg-overlay);box-shadow:0 18px 60px rgba(0,0,0,.35);overflow:hidden}',
3726
3758
  '.rw-modal-head{display:flex;align-items:center;gap:10px;padding:14px 16px;border-bottom:1px solid var(--dsw-alias-border-l1)}',
@@ -3739,6 +3771,11 @@ function attributeViolation(name, value, tagName) {
3739
3771
  '.rw-sync-tag{flex:none;min-width:52px;color:rgb(150,150,152)}',
3740
3772
  '.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
3773
  '.rw-autopush-list{width:100%;resize:vertical;font-family:var(--dsw-font-mono,monospace);font-size:12px}',
3774
+ '.rw-known-keys{display:flex;flex-direction:column;gap:6px;margin-top:8px}',
3775
+ '.rw-known-key{display:flex;align-items:center;gap:10px}',
3776
+ '.rw-known-key-main{flex:1 1 auto;min-width:0;display:flex;flex-direction:column;gap:2px}',
3777
+ '.rw-known-key-host{font-size:12px;color:var(--dsw-alias-text-2)}',
3778
+ '.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
3779
  '.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
3780
  '.rw-exec-item input[type=checkbox]{margin:0;flex:none}',
3744
3781
  '.rw-exec-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
@@ -6470,7 +6507,7 @@ function rememberShowHidden(value) {
6470
6507
  { main: t('welcomeTools'), where: t('welcomeToolsWhere') },
6471
6508
  { main: t('welcomePassword'), where: t('welcomePasswordWhere') },
6472
6509
  ];
6473
- return h('div', {
6510
+ return h(PortalBackdrop, {
6474
6511
  className: 'rw-welcome-backdrop',
6475
6512
  onMouseDown: function (event) { if (event.target === event.currentTarget) close(); },
6476
6513
  }, h('div', {
@@ -6501,6 +6538,80 @@ function rememberShowHidden(value) {
6501
6538
  h('button', { type: 'button', className: 'rw-btn', onClick: close }, t('welcomeDone')))));
6502
6539
  }
6503
6540
 
6541
+ /**
6542
+ * Host for every overlay this plugin draws.
6543
+ *
6544
+ * DSH renders plugin slots inside its own layout tree, and the session column
6545
+ * (composer included) paints above neighbouring columns. A `position: fixed`
6546
+ * overlay that stays in the slot subtree is therefore still trapped by the
6547
+ * stacking context of its ancestor chain: raising z-index only wins against
6548
+ * some panes, never against a later top-layer or a higher ancestor context.
6549
+ *
6550
+ * So the overlay is portalled into a native <dialog> opened with showModal(),
6551
+ * which lives in the browser's top layer and paints above every column and
6552
+ * every future overlay regardless of z-index. When react-dom is missing (or the
6553
+ * browser has no <dialog>), it falls back to the in-place node, which still
6554
+ * works as before.
6555
+ */
6556
+ function PortalBackdrop(props) {
6557
+ var hostState = useState(null);
6558
+ var host = hostState[0];
6559
+ var setHost = hostState[1];
6560
+ var hostRef = useRef(null);
6561
+ var canPortal = Boolean(
6562
+ reactDom
6563
+ && typeof reactDom.createPortal === 'function'
6564
+ && typeof document !== 'undefined'
6565
+ && typeof document.createElement === 'function',
6566
+ );
6567
+
6568
+ useEffect(function () {
6569
+ if (!canPortal) return undefined;
6570
+ var element = document.createElement('dialog');
6571
+ element.className = 'rw-top-layer';
6572
+ element.setAttribute('data-lw-top-layer', '1');
6573
+ // Esc has to leave through React: the overlay owns its own cleanup, so if
6574
+ // the browser closed the <dialog> on its own the component would keep
6575
+ // rendering into a closed host. Every close path is funnelled to
6576
+ // props.onEscape instead.
6577
+ var onCancel = function (event) {
6578
+ if (event && typeof event.preventDefault === 'function') event.preventDefault();
6579
+ if (props.onEscape) props.onEscape();
6580
+ };
6581
+ var onNativeClose = function () {
6582
+ if (props.onEscape) props.onEscape();
6583
+ };
6584
+ element.addEventListener('cancel', onCancel);
6585
+ element.addEventListener('close', onNativeClose);
6586
+ document.body.appendChild(element);
6587
+ try {
6588
+ if (typeof element.showModal === 'function') element.showModal();
6589
+ else element.setAttribute('open', '');
6590
+ } catch (error) {
6591
+ element.setAttribute('open', '');
6592
+ }
6593
+ hostRef.current = element;
6594
+ setHost(element);
6595
+ return function () {
6596
+ hostRef.current = null;
6597
+ element.removeEventListener('cancel', onCancel);
6598
+ element.removeEventListener('close', onNativeClose);
6599
+ try { if (typeof element.close === 'function') element.close(); } catch (error) { /* already closed */ }
6600
+ if (element.parentNode) element.parentNode.removeChild(element);
6601
+ };
6602
+ }, [canPortal]);
6603
+
6604
+ var node = h('div', {
6605
+ className: props.className,
6606
+ role: props.role,
6607
+ onMouseDown: props.onMouseDown,
6608
+ }, props.children);
6609
+
6610
+ if (!canPortal) return node;
6611
+ if (!host) return null;
6612
+ return reactDom.createPortal(node, host);
6613
+ }
6614
+
6504
6615
  function DialogShell(props) {
6505
6616
  var boxRef = useRef(null);
6506
6617
  var restoreRef = useRef(null);
@@ -6542,7 +6653,7 @@ function rememberShowHidden(value) {
6542
6653
  window.addEventListener('keydown', onKey, true);
6543
6654
  return function () { window.removeEventListener('keydown', onKey, true); };
6544
6655
  }, [props.onClose]);
6545
- return h('div', {
6656
+ return h(PortalBackdrop, {
6546
6657
  className: 'rw-dialog-backdrop',
6547
6658
  onMouseDown: function (event) { if (event.target === event.currentTarget) props.onClose(); },
6548
6659
  }, h('div', {
@@ -10155,6 +10266,21 @@ function rememberShowHidden(value) {
10155
10266
  return function () { window.removeEventListener('wheel', onWheel, { capture: true }); };
10156
10267
  }, [props.open]);
10157
10268
 
10269
+ // Esc has to be caught on the window: the overlay now lives in a top-layer
10270
+ // <dialog>, so key events start at that element and never reach the modal
10271
+ // div's own handler.
10272
+ useEffect(function () {
10273
+ if (!props.open) return undefined;
10274
+ function onKey(event) {
10275
+ if (event.key !== 'Escape') return;
10276
+ event.preventDefault();
10277
+ event.stopPropagation();
10278
+ if (props.onCancel) props.onCancel();
10279
+ }
10280
+ window.addEventListener('keydown', onKey, true);
10281
+ return function () { window.removeEventListener('keydown', onKey, true); };
10282
+ }, [props.open, props.onCancel]);
10283
+
10158
10284
  function onModalKeyDown(event) {
10159
10285
  if (event.key === 'Escape') {
10160
10286
  event.preventDefault();
@@ -10180,7 +10306,11 @@ function rememberShowHidden(value) {
10180
10306
 
10181
10307
  if (!props.open) return null;
10182
10308
 
10183
- return h('div', { className: 'rw-modal-backdrop', role: 'presentation' },
10309
+ return h(PortalBackdrop, {
10310
+ className: 'rw-modal-backdrop',
10311
+ role: 'presentation',
10312
+ onEscape: function () { if (props.onCancel) props.onCancel(); },
10313
+ },
10184
10314
  h('div', {
10185
10315
  ref: modalRef,
10186
10316
  className: 'rw-modal',
@@ -11094,6 +11224,140 @@ function rememberShowHidden(value) {
11094
11224
  return h('div', { className: 'rw-group' }, children);
11095
11225
  }
11096
11226
 
11227
+ /**
11228
+ * Host key trust and command-output encoding (0.20.0).
11229
+ *
11230
+ * Before this, a changed host key could only be cleared by hand-editing
11231
+ * `known_hosts.json`, and a Windows shell's GBK output arrived as mojibake.
11232
+ */
11233
+ function SshTrustSettingsGroup(props) {
11234
+ var t = props.t;
11235
+ var locale = props.locale;
11236
+ var localState = useState({ loading: true, saving: false, message: null });
11237
+ var local = localState[0];
11238
+ var setLocal = localState[1];
11239
+ var valuesState = useState({ hostKeyPolicy: 'tofu', outputEncoding: 'utf8' });
11240
+ var values = valuesState[0];
11241
+ var setValues = valuesState[1];
11242
+ var keysState = useState([]);
11243
+ var keys = keysState[0];
11244
+ var setKeys = keysState[1];
11245
+
11246
+ function refreshKeys() {
11247
+ apiCall('hosts.hostKeys', {}).then(function (result) {
11248
+ setKeys(Array.isArray(result.entries) ? result.entries : []);
11249
+ }).catch(function () {
11250
+ setKeys([]);
11251
+ });
11252
+ }
11253
+
11254
+ useEffect(function () {
11255
+ var alive = true;
11256
+ apiCall('settings.get', {}).then(function (settings) {
11257
+ if (!alive) return;
11258
+ setValues({
11259
+ hostKeyPolicy: settings.hostKeyPolicy === 'strict' ? 'strict' : 'tofu',
11260
+ outputEncoding: settings.outputEncoding === 'gbk' ? 'gbk' : 'utf8',
11261
+ });
11262
+ setLocal(function (previous) { return Object.assign({}, previous, { loading: false }); });
11263
+ }).catch(function () {
11264
+ if (alive) setLocal(function (previous) { return Object.assign({}, previous, { loading: false }); });
11265
+ });
11266
+ refreshKeys();
11267
+ return function () { alive = false; };
11268
+ }, []);
11269
+
11270
+ function save(patch, okText) {
11271
+ setLocal(function (previous) { return Object.assign({}, previous, { saving: true, message: null }); });
11272
+ apiCall('settings.update', patch).then(function (settings) {
11273
+ setValues({
11274
+ hostKeyPolicy: settings.hostKeyPolicy === 'strict' ? 'strict' : 'tofu',
11275
+ outputEncoding: settings.outputEncoding === 'gbk' ? 'gbk' : 'utf8',
11276
+ });
11277
+ setLocal({ loading: false, saving: false, message: { kind: 'success', text: okText } });
11278
+ }).catch(function (error) {
11279
+ setLocal({ loading: false, saving: false, message: { kind: 'error', text: messageOf(error, t, locale) } });
11280
+ });
11281
+ }
11282
+
11283
+ function forget(entry) {
11284
+ var params = entry.hostId ? { hostId: entry.hostId } : { authority: entry.authority };
11285
+ setLocal(function (previous) { return Object.assign({}, previous, { saving: true, message: null }); });
11286
+ apiCall('hosts.forgetHostKey', params).then(function () {
11287
+ setLocal({
11288
+ loading: false,
11289
+ saving: false,
11290
+ message: { kind: 'success', text: t('forgotHostKey', { authority: entry.authority }) },
11291
+ });
11292
+ refreshKeys();
11293
+ }).catch(function (error) {
11294
+ setLocal({ loading: false, saving: false, message: { kind: 'error', text: messageOf(error, t, locale) } });
11295
+ });
11296
+ }
11297
+
11298
+ var children = [
11299
+ h('div', { className: 'rw-group-head' },
11300
+ h('span', { className: 'rw-group-title' }, t('sshTrustTitle')),
11301
+ local.saving ? Spinner(12) : null),
11302
+ h('div', { className: 'rw-group-hint' }, t('sshTrustHint')),
11303
+ h('div', { className: 'rw-inline', style: { marginTop: 10, flexWrap: 'wrap', gap: 12 } },
11304
+ h('span', { className: 'rw-setting-label' }, t('hostKeyPolicyLabel')),
11305
+ h('select', {
11306
+ className: 'rw-input',
11307
+ value: values.hostKeyPolicy,
11308
+ onChange: function (event) {
11309
+ var next = event.currentTarget.value;
11310
+ setValues(function (previous) { return Object.assign({}, previous, { hostKeyPolicy: next }); });
11311
+ save({ hostKeyPolicy: next }, t('sshTrustSaved'));
11312
+ },
11313
+ },
11314
+ h('option', { value: 'tofu' }, t('hostKeyPolicyTofu')),
11315
+ h('option', { value: 'strict' }, t('hostKeyPolicyStrict')))),
11316
+ h('div', { className: 'rw-inline', style: { marginTop: 10, flexWrap: 'wrap', gap: 12 } },
11317
+ h('span', { className: 'rw-setting-label' }, t('outputEncodingLabel')),
11318
+ h('select', {
11319
+ className: 'rw-input',
11320
+ value: values.outputEncoding,
11321
+ onChange: function (event) {
11322
+ var next = event.currentTarget.value;
11323
+ setValues(function (previous) { return Object.assign({}, previous, { outputEncoding: next }); });
11324
+ save({ outputEncoding: next }, t('sshTrustSaved'));
11325
+ },
11326
+ },
11327
+ h('option', { value: 'utf8' }, t('outputEncodingUtf8')),
11328
+ h('option', { value: 'gbk' }, t('outputEncodingGbk')))),
11329
+ h('div', { className: 'rw-group-head', style: { marginTop: 14 } },
11330
+ h('span', { className: 'rw-group-title' }, t('knownKeysTitle'))),
11331
+ ];
11332
+
11333
+ if (keys.length === 0) {
11334
+ children.push(h('div', { className: 'rw-group-hint' }, t('knownKeysEmpty')));
11335
+ } else {
11336
+ children.push(h('div', { className: 'rw-known-keys' }, keys.map(function (entry) {
11337
+ return h('div', { className: 'rw-known-key', key: entry.authority },
11338
+ h('div', { className: 'rw-known-key-main' },
11339
+ h('span', { className: 'rw-known-key-host' }, entry.hostName ? entry.hostName + ' · ' + entry.authority : entry.authority),
11340
+ h('span', { className: 'rw-known-key-fp', title: entry.fingerprint }, entry.fingerprint)),
11341
+ h('button', {
11342
+ type: 'button',
11343
+ className: 'rw-btn rw-btn-sm',
11344
+ onClick: function () { forget(entry); },
11345
+ }, t('forgetHostKey')));
11346
+ })));
11347
+ }
11348
+
11349
+ if (local.message) {
11350
+ children.push(h(Banner, {
11351
+ kind: local.message.kind === 'success' ? 'success' : 'error',
11352
+ onClose: function () {
11353
+ setLocal(function (previous) { return Object.assign({}, previous, { message: null }); });
11354
+ },
11355
+ }, local.message.text));
11356
+ }
11357
+
11358
+ return h('div', { className: 'rw-group' }, children);
11359
+ }
11360
+
11097
11361
  function ConnectionsPage(props) {
11098
11362
  var ctx = props.ctx;
11099
11363
  var locale = useLocale(ctx);
@@ -11161,6 +11425,7 @@ function rememberShowHidden(value) {
11161
11425
  workspaces: links.concat(remotes),
11162
11426
  }),
11163
11427
  h(AutoPushSettingsGroup, { t: t, locale: locale }),
11428
+ h(SshTrustSettingsGroup, { t: t, locale: locale }),
11164
11429
  adding === 'linked'
11165
11430
  ? h(AddWorkspaceFlow, {
11166
11431
  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.1",
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",