Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat(remote): SSH 与远端访问统一化为 dsh-tauri-remote(S1–S6) (#990)

Atlas Zenge0b8f25fab7b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e0f1182d..947a27e1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -137,10 +137,18 @@ jobs:
# 0.1.6 起上游改了设置侧栏分区名与未分组 chip 等文案,另需一轮 e2e 适配。
npm install --no-audit --no-fund @deepseek-ai/[email protected]
+ # dsh-tauri-remote 的入站暴露用例按当前内核(dsh-h3 设置分区与面板)写就,
+ # 与 extension-panel 同口径:legacy 内核排除,改由「Host and migrated plugin contracts」批次跑。
- name: Plugin L2 test (legacy core)
env:
DSH_E2E_DSH_BIN: ${{ runner.temp }}/dsh-cli/node_modules/@deepseek-ai/dsh/lib/bin.js
- run: node node_modules/vitest/vitest.mjs run --project plugin --exclude test/e2e/plugins/dsh-tauri-extension-panel.e2e.ts --exclude test/e2e/plugins/dsh-tauri-scheduler.e2e.ts --exclude test/e2e/plugins/dsh-tauri-scheduler-client.e2e.ts
+ run: |
+ node node_modules/vitest/vitest.mjs run --project plugin \
+ --exclude test/e2e/plugins/dsh-tauri-extension-panel.e2e.ts \
+ --exclude test/e2e/plugins/dsh-tauri-scheduler.e2e.ts \
+ --exclude test/e2e/plugins/dsh-tauri-scheduler-client.e2e.ts \
+ --exclude test/e2e/plugins/dsh-tauri-remote-access.e2e.ts \
+ --exclude test/e2e/plugins/dsh-tauri-remote-panel.e2e.ts
- name: Mobile settings composition (legacy core)
env:
@@ -164,7 +172,7 @@ jobs:
- name: Host and migrated plugin contracts (current core)
env:
DSH_E2E_DSH_BIN: ${{ runner.temp }}/dsh-cli-current/node_modules/@deepseek-ai/dsh/lib/bin.js
- run: node node_modules/vitest/vitest.mjs run --project plugin test/e2e/plugins/dsh-host-and-core-contract.e2e.ts test/e2e/plugins/dsh-tauri-model.e2e.ts test/e2e/plugins/dsh-tauri-worktree.e2e.ts test/e2e/plugins/dsh-tauri-experimental.e2e.ts
+ run: node node_modules/vitest/vitest.mjs run --project plugin test/e2e/plugins/dsh-host-and-core-contract.e2e.ts test/e2e/plugins/dsh-tauri-model.e2e.ts test/e2e/plugins/dsh-tauri-worktree.e2e.ts test/e2e/plugins/dsh-tauri-experimental.e2e.ts test/e2e/plugins/dsh-tauri-remote-access.e2e.ts test/e2e/plugins/dsh-tauri-remote-panel.e2e.ts
- name: Unified scheduler host and right-sidebar contracts (current core)
id: scheduler_contracts
diff --git a/.gitmodules b/.gitmodules
index 0d58c9de..f230b527 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -46,3 +46,6 @@
[submodule "source/relay-dsh-plugin-claude"]
path = source/relay-dsh-plugin-claude
url = https://github.com/yangbobo2021/relay-dsh-plugin-claude.git
+[submodule "soruce/dsh-bridge"]
+ path = soruce/dsh-bridge
+ url = https://github.com/wenbin-wb/dsh-bridge.git
diff --git a/README.en.md b/README.en.md
index c13cda07..1d4864ce 100644
--- a/README.en.md
+++ b/README.en.md
@@ -70,7 +70,7 @@ First-party plugins distributed with desktop resources:
- [DSH Tauri Pet](https://dshtauri.mintlify.site/en/built-in-plugins/dsh-tauri-pet) — Desktop pet and activity state settings
- [DSH Tauri Rightclick Menu](https://dshtauri.mintlify.site/en/built-in-plugins/dsh-tauri-rightclick) — Session, workspace, and text context menus
- [DSH Tauri Model](https://dshtauri.mintlify.site/en/built-in-plugins/dsh-tauri-model) — Model selection, parameters, and automatic configuration
-- [DSH Tauri SSH](https://dshtauri.mintlify.site/en/built-in-plugins/dsh-tauri-ssh) — Remote Harness connections and sync over SSH
+- [DSH Tauri Remote](https://dshtauri.mintlify.site/en/built-in-plugins/dsh-tauri-remote) — Remote Harness connections and sync over SSH, plus sharing the local Harness over LAN or a public tunnel
- [DSH Tauri Notification](https://dshtauri.mintlify.site/en/built-in-plugins/dsh-tauri-notification) — Conversation notifications and actions
## Optional presets
diff --git a/README.es.md b/README.es.md
index bb794b36..8f4edf4c 100644
--- a/README.es.md
+++ b/README.es.md
@@ -70,7 +70,7 @@ Plugins propios distribuidos con los recursos del escritorio:
- [DSH Tauri Pet](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-pet) — Ajustes de mascotas y estados de actividad
- [DSH Tauri Rightclick Menu](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-rightclick) — Menús contextuales de sesiones, workspaces y texto
- [DSH Tauri Model](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-model) — Selección de modelos, parámetros y configuración automática
-- [DSH Tauri SSH](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-ssh) — Conexiones Harness remotas y sincronización por SSH
+- [DSH Tauri Remote](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-remote) — Conexiones Harness remotas y sincronización por SSH, además de compartir el Harness local por LAN o túnel público
- [DSH Tauri Notification](https://github.com/dsh-tauri/deepseek-harness-desktop/tree/main/packages/dsh-tauri-notification) — Notificaciones de conversaciones y acciones
## Preajustes opcionales
diff --git a/README.md b/README.md
index 393f1b36..f4278955 100644
--- a/README.md
+++ b/README.md
@@ -69,7 +69,7 @@
- [DSH Tauri Pet](https://dshtauri.mintlify.site/zh-CN/built-in-plugins/dsh-tauri-pet) — 桌宠与活动状态设置
- [DSH Tauri Rightclick Menu](https://dshtauri.mintlify.site/zh-CN/built-in-plugins/dsh-tauri-rightclick) — 会话、工作区与正文右键菜单
- [DSH Tauri Model](https://dshtauri.mintlify.site/zh-CN/built-in-plugins/dsh-tauri-model) — 模型选择与参数、自动配置模型
-- [DSH Tauri SSH](https://dshtauri.mintlify.site/zh-CN/built-in-plugins/dsh-tauri-ssh) — SSH 远端 Harness 连接与同步
+- [DSH Tauri Remote](https://dshtauri.mintlify.site/zh-CN/built-in-plugins/dsh-tauri-remote) — SSH 远端 Harness 连接与同步,并把本机 Harness 分享到局域网或公网隧道
- [DSH Tauri Notification](https://dshtauri.mintlify.site/zh-CN/built-in-plugins/dsh-tauri-notification) — 原生级会话通知与交互操作
## 可选预设
diff --git a/docs/specs/plugin.client.md b/docs/specs/plugin.client.md
index 0c2349ab..b20462e9 100644
--- a/docs/specs/plugin.client.md
+++ b/docs/specs/plugin.client.md
@@ -108,7 +108,7 @@ $$\text{client/index.ts} \longrightarrow \begin{bmatrix} \text{register/} \\ \te
### 5. API 层 (`apis/`)
* **唯一允许发请求的层**。JSON 请求使用 `dsh-tauri/client` 导出的 `ofetch`(与既有 `fetch` 为同一 JSON 实例,不是流式传输);严禁使用 `axios` 或 `window.fetch`。
-* `apis/index.ts` 与 `apis/index.type.ts` 由根目录 `genapi.config.ts` 使用 `dsh-h3/genapi` 从 `host/server/index.ts` 生成,修改服务契约后运行 `pnpm genapi`,禁止手改生成结果或恢复 `genapi.pipeline.ts`。插件路径统一为 `/api/tauri/<插件短名>`(如 `/api/tauri/ssh/machines`),生成类型与消费方按新路径同步,不建立旧 URL 或 DTO 名别名。
+* `apis/index.ts` 与 `apis/index.type.ts` 由根目录 `genapi.config.ts` 使用 `dsh-h3/genapi` 从 `host/server/index.ts` 生成,修改服务契约后运行 `pnpm genapi`,禁止手改生成结果或恢复 `genapi.pipeline.ts`。插件路径统一为 `/api/tauri/<插件短名>`(如 `/api/tauri/remote/machines`),生成类型与消费方按新路径同步,不建立旧 URL 或 DTO 名别名。
* 请求函数名使用 `HTTP动词 + 路径领域名词`,通过根配置的 transform/patch 保持必要的既有操作名;body/query 必须传入生成函数对应参数,不能误当请求 options。业务类型可从生成响应的成功分支派生,保留真实错误联合,不复制另一套 DTO。
* 保持现有 JSON 传输:插件生成文件使用 `dsh-tauri/client` 的 `ofetch` 与 type-only `FetchOptions`;桌面壳 SSH 的 `src/apis/remote.ts` 使用 `./http` 的 invoke 适配,不改用浏览器原生 fetch。
diff --git a/genapi.config.ts b/genapi.config.ts
index bfd271e8..ac053b06 100644
--- a/genapi.config.ts
+++ b/genapi.config.ts
@@ -13,7 +13,7 @@ const plugins = [
'dsh-tauri-ui',
'dsh-tauri-notification',
'dsh-tauri-worktree',
- 'dsh-tauri-ssh',
+ 'dsh-tauri-remote',
'dsh-tauri-kernel',
]
@@ -37,7 +37,7 @@ export default defineConfig({
),
meta: { import: { http: 'dsh-tauri/client' } },
transform: {
- operation: name => name.replace(/ApiTauri(?:Extension|Scheduler|Rightclick|Archive|Experimental|Model|Ui|Notification|Worktree|Ssh|Bridge)/, ''),
+ operation: name => name.replace(/ApiTauri(?:Extension|Scheduler|Rightclick|Archive|Experimental|Model|Ui|Notification|Worktree|Bridge|Remote)/, ''),
},
patch: { operations: { post: 'postWorktree', delete: 'deleteWorktree' } },
servers: [
@@ -49,7 +49,7 @@ export default defineConfig({
},
})),
{
- input: 'packages/dsh-tauri-ssh/src/host/server/index.ts',
+ input: 'packages/dsh-tauri-remote/src/host/server/index.ts',
output: { main: 'src/apis/remote.ts', type: 'src/apis/remote.types.ts' },
meta: { import: { http: './http' } },
},
diff --git a/packages/dsh-tauri-bundle/package.json b/packages/dsh-tauri-bundle/package.json
index a75212d0..8c43c814 100644
--- a/packages/dsh-tauri-bundle/package.json
+++ b/packages/dsh-tauri-bundle/package.json
@@ -11,9 +11,9 @@
"dsh-tauri-model": "workspace:*",
"dsh-tauri-notification": "workspace:*",
"dsh-tauri-pet": "workspace:*",
+ "dsh-tauri-remote": "workspace:*",
"dsh-tauri-rightclick": "workspace:*",
"dsh-tauri-scheduler": "workspace:*",
- "dsh-tauri-ssh": "workspace:*",
"dsh-tauri-ui": "workspace:*",
"dsh-tauri-worktree": "workspace:*"
}
diff --git a/packages/dsh-tauri-notification/src/client/register/settings.test.ts b/packages/dsh-tauri-notification/src/client/register/settings.test.ts
index 3131ed78..a06688c2 100644
--- a/packages/dsh-tauri-notification/src/client/register/settings.test.ts
+++ b/packages/dsh-tauri-notification/src/client/register/settings.test.ts
@@ -5,7 +5,7 @@ import { SETTINGS_GENERAL_ITEM_ID, SETTINGS_GENERAL_ITEM_ORDER, SETTINGS_GENERAL
import { settingsFeature } from './settings'
// 真 `defineRegister` 会在 effect 运行时创建控制器与适配器;这里只验证注册形状,
-// 直接拿 setup 回调调用即可(与 `dsh-tauri-ssh` 的注册测试同一套路)。
+// 直接拿 setup 回调调用即可(与 `dsh-tauri-remote` 的注册测试同一套路)。
vi.mock('dsh-tauri/client', () => ({
defineLocale: (ns: string, dictionaries: Record<string, unknown>) => ({ NS: ns, ...dictionaries }),
defineRegister: (setup: unknown) => setup,
diff --git a/packages/dsh-tauri-remote/cordis.patch.yml b/packages/dsh-tauri-remote/cordis.patch.yml
new file mode 100644
index 00000000..11b0e0ab
--- /dev/null
+++ b/packages/dsh-tauri-remote/cordis.patch.yml
@@ -0,0 +1,3 @@
+- insert:
+ - id: dsh-tauri-remote
+ name: dsh-tauri-remote
diff --git a/packages/dsh-tauri-ssh/package.json b/packages/dsh-tauri-remote/package.json
similarity index 87%
rename from packages/dsh-tauri-ssh/package.json
rename to packages/dsh-tauri-remote/package.json
index b1deba03..c687b8c4 100644
--- a/packages/dsh-tauri-ssh/package.json
+++ b/packages/dsh-tauri-remote/package.json
@@ -1,11 +1,11 @@
{
- "name": "dsh-tauri-ssh",
+ "name": "dsh-tauri-remote",
"type": "module",
"version": "0.6.7",
- "description": "DSH 远程主机宿主插件:SSH 连接管理(TOFU 主机密钥、~/.ssh/config 自动发现)、远程 dsh web 自动启动、回环隧道、/api/desktop/dsh-tauri-ssh REST 路由,以及机器增删改、连接/测试/断开与一键远程安装的设置页。",
+ "description": "DSH 远程主机宿主插件:SSH 连接管理(TOFU 主机密钥、~/.ssh/config 自动发现)、远程 dsh web 自动启动、回环隧道、/api/tauri/remote REST 路由,以及机器增删改、连接/测试/断开与一键远程安装的设置页。",
"author": "Hairyf <[email protected]>",
"license": "MIT",
- "homepage": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-ssh",
+ "homepage": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-remote",
"repository": {
"type": "git",
"url": "git+https://github.com/dsh-tauri-desk/deepseek-harness-desktop.git"
@@ -17,7 +17,7 @@
"dsh",
"plugin",
"dsh-plugin",
- "ssh",
+ "remote",
"remote",
"tauri",
"deepseek-harness"
@@ -75,11 +75,13 @@
"@testing-library/dom": "catalog:testing",
"@testing-library/react": "catalog:testing",
"@types/node": "catalog:types",
+ "@types/qrcode": "catalog:types",
"@types/react": "catalog:types",
"@types/react-dom": "catalog:types",
"@types/ssh2": "catalog:types",
"dsh-tauri-tsdown": "workspace:*",
"jsdom": "catalog:testing",
+ "qrcode": "catalog:utils",
"react": "catalog:runtime",
"react-dom": "catalog:runtime",
"tsdown": "catalog:cli",
diff --git a/packages/dsh-tauri-ssh/src/client/apis/index.test.ts b/packages/dsh-tauri-remote/src/client/apis/index.test.ts
similarity index 98%
rename from packages/dsh-tauri-ssh/src/client/apis/index.test.ts
rename to packages/dsh-tauri-remote/src/client/apis/index.test.ts
index 2e745bd6..79f2ba63 100644
--- a/packages/dsh-tauri-ssh/src/client/apis/index.test.ts
+++ b/packages/dsh-tauri-remote/src/client/apis/index.test.ts
@@ -5,9 +5,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
import * as api from './index'
+const baseURL = '/api/tauri/remote'
+
vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
-const API = '/api/tauri/ssh'
+const API = baseURL
const machineA: MachineRow = {
id: 'a',
diff --git a/packages/dsh-tauri-remote/src/client/apis/index.ts b/packages/dsh-tauri-remote/src/client/apis/index.ts
new file mode 100644
index 00000000..0362a0cc
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/apis/index.ts
@@ -0,0 +1,94 @@
+/*
+ * @title index
+ * @swagger 2.0
+ * @version 0.0.0
+ */
+
+import type * as Types from "./index.type";
+import { ofetch } from "dsh-tauri/client";
+import type { FetchOptions } from "dsh-tauri/client";
+
+/** @method get */
+export function getSettings(options?: FetchOptions) {
+ return ofetch<Types.GetApiTauriRemoteSettingsResponse>("/api/tauri/remote/settings", { method: "get", ...options });
+}
+
+/** @method post */
+export function postSettings(body: Types.PostApiTauriRemoteSettingsBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteSettingsResponse>("/api/tauri/remote/settings", { method: "post", body, ...options });
+}
+
+/** @method get */
+export function getSessionRole(options?: FetchOptions) {
+ return ofetch<Types.GetApiTauriRemoteSessionRoleResponse>("/api/tauri/remote/session/role", { method: "get", ...options });
+}
+
+/** @method get */
+export function getMachines(options?: FetchOptions) {
+ return ofetch<Types.GetApiTauriRemoteMachinesResponse>("/api/tauri/remote/machines", { method: "get", ...options });
+}
+
+/** @method post */
+export function postMachines(body: Types.PostApiTauriRemoteMachinesBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteMachinesResponse>("/api/tauri/remote/machines", { method: "post", body, ...options });
+}
+
+/** @method delete */
+export function deleteMachines(body: Types.DeleteApiTauriRemoteMachinesBody, options?: FetchOptions) {
+ return ofetch<Types.DeleteApiTauriRemoteMachinesResponse>("/api/tauri/remote/machines", { method: "delete", body, ...options });
+}
+
+/** @method post */
+export function postMachinesTest(body: Types.PostApiTauriRemoteMachinesTestBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteMachinesTestResponse>("/api/tauri/remote/machines/test", { method: "post", body, ...options });
+}
+
+/** @method post */
+export function postMachinesConnect(body: Types.PostApiTauriRemoteMachinesConnectBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteMachinesConnectResponse>("/api/tauri/remote/machines/connect", { method: "post", body, ...options });
+}
+
+/** @method post */
+export function postMachinesDisconnect(body: Types.PostApiTauriRemoteMachinesDisconnectBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteMachinesDisconnectResponse>("/api/tauri/remote/machines/disconnect", { method: "post", body, ...options });
+}
+
+/** @method post */
+export function postMachinesInstall(body: Types.PostApiTauriRemoteMachinesInstallBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteMachinesInstallResponse>("/api/tauri/remote/machines/install", { method: "post", body, ...options });
+}
+
+/** @method get */
+export function getMachinesEvents(params?: Types.GetApiTauriRemoteMachinesEventsQuery, options?: FetchOptions) {
+ return ofetch<Types.GetApiTauriRemoteMachinesEventsResponse>("/api/tauri/remote/machines/events", { method: "get", params, ...options });
+}
+
+/** @method get */
+export function getSyncPreview(options?: FetchOptions) {
+ return ofetch<Types.GetApiTauriRemoteSyncPreviewResponse>("/api/tauri/remote/sync/preview", { method: "get", ...options });
+}
+
+/** @method post */
+export function postSyncApply(body: Types.PostApiTauriRemoteSyncApplyBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteSyncApplyResponse>("/api/tauri/remote/sync/apply", { method: "post", body, ...options });
+}
+
+/** @method get */
+export function getAccess(params?: Types.GetApiTauriRemoteAccessQuery, options?: FetchOptions) {
+ return ofetch<Types.GetApiTauriRemoteAccessResponse>("/api/tauri/remote/access", { method: "get", params, ...options });
+}
+
+/** @method post */
+export function postAccess(body: Types.PostApiTauriRemoteAccessBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteAccessResponse>("/api/tauri/remote/access", { method: "post", body, ...options });
+}
+
+/** @method post */
+export function postAccessTunnel(body: Types.PostApiTauriRemoteAccessTunnelBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteAccessTunnelResponse>("/api/tauri/remote/access/tunnel", { method: "post", body, ...options });
+}
+
+/** @method delete */
+export function deleteAccessTunnel(options?: FetchOptions) {
+ return ofetch<Types.DeleteApiTauriRemoteAccessTunnelResponse>("/api/tauri/remote/access/tunnel", { method: "delete", ...options });
+}
diff --git a/packages/dsh-tauri-remote/src/client/apis/index.type.ts b/packages/dsh-tauri-remote/src/client/apis/index.type.ts
new file mode 100644
index 00000000..68e871c1
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/apis/index.type.ts
@@ -0,0 +1,164 @@
+export type GetApiTauriRemoteSettingsResponse = { enabled?: false | true; error?: string };
+export type PostApiTauriRemoteSettingsResponse = { enabled?: false | true; error?: string };
+export type GetApiTauriRemoteSessionRoleResponse = { role?: string; remote?: false | true; origin?: string; error?: string };
+export type GetApiTauriRemoteMachinesResponse = {
+ enabled?: false | true;
+ items?: { id?: string; name?: string; host?: string; port?: number; user?: string; hasPassword?: false | true; hasPassphrase?: false | true; remotePort?: number; profileName?: string; startCommand?: string; color?: string; tintBorder?: false | true; state?: "disconnected" | "testing" | "connecting" | "connected" | "reconnecting" | "given-up"; tunnelBaseUrl?: string; lastError?: string; dshMissing?: false | true; progress?: { phase: "handshake" | "starting" | "probing" | "installing" | "syncing"; attempt?: number; total?: number; item?: string; log?: string }; nextRetryAt?: number; authMethod?: "agent" | "key" | "password" }[];
+ discovered?: { id?: string; name?: string; host?: string; port?: number; user?: string; hasPassword?: false | true; hasPassphrase?: false | true; remotePort?: number; profileName?: string; startCommand?: string; color?: string; tintBorder?: false | true; state?: "disconnected" | "testing" | "connecting" | "connected" | "reconnecting" | "given-up"; tunnelBaseUrl?: string; lastError?: string; dshMissing?: false | true; progress?: { phase: "handshake" | "starting" | "probing" | "installing" | "syncing"; attempt?: number; total?: number; item?: string; log?: string }; nextRetryAt?: number; authMethod?: "agent" | "key" | "password" }[];
+ error?: string;
+};
+export type PostApiTauriRemoteMachinesResponse = { error?: string };
+export type DeleteApiTauriRemoteMachinesResponse = { error?: string };
+export type PostApiTauriRemoteMachinesTestResponse = { ok?: false | true; banner?: string; message?: string; error?: string };
+export type PostApiTauriRemoteMachinesConnectResponse = { tunnelBaseUrl?: string; error?: string };
+export type PostApiTauriRemoteMachinesDisconnectResponse = { error?: string };
+export type PostApiTauriRemoteMachinesInstallResponse = { installed?: string[]; dshRef?: string; dshVersion?: string; dshPath?: string; credentialsCopied?: false | true; credentialsError?: string; error?: string };
+export type GetApiTauriRemoteMachinesEventsResponse = { items?: { seq?: number; ts?: string; machineId?: string; stage?: string; line?: string; terminal?: string; reason?: string }[]; nextSeq?: number; error?: string };
+export type GetApiTauriRemoteMachinesEventsQueryMachineId = string;
+export type GetApiTauriRemoteMachinesEventsQuerySinceSeq = number;
+export type GetApiTauriRemoteSyncPreviewResponse = { plugins?: { name?: string; spec?: string; syncable?: false | true; reason?: string }[]; skills?: { name?: string; root?: string }[]; error?: string };
+export type PostApiTauriRemoteSyncApplyResponse = { items?: { kind?: string; name?: string; root?: string; ok?: false | true; error?: string; log?: string }[]; error?: string };
+export type GetApiTauriRemoteAccessResponse = {
+ version: number;
+ enabled: false | true;
+ state: "error" | "stopped" | "listening";
+ listening: false | true;
+ listen: { address: string; port: number };
+ port: number;
+ auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };
+ addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];
+ recommended?: string;
+ link?: string;
+ maskLink?: string;
+ qr?: string;
+ linkSource?: "loopback" | "lan";
+ pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };
+ generatedPassword?: string;
+ tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };
+ localPort?: number;
+ error?: string;
+ warnings?: string[];
+ events: { seq: number; ts: string; kind: "auth" | "token" | "state"; line: string }[];
+};
+export type GetApiTauriRemoteAccessQuerySincePairingUseSeq = number;
+export type PostApiTauriRemoteAccessResponse =
+ | {
+ version: number;
+ enabled: false | true;
+ state: "error" | "stopped" | "listening";
+ listening: false | true;
+ listen: { address: string; port: number };
+ port: number;
+ auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };
+ addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];
+ recommended?: string;
+ link?: string;
+ maskLink?: string;
+ qr?: string;
+ linkSource?: "loopback" | "lan";
+ pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };
+ generatedPassword?: string;
+ tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };
+ localPort?: number;
+ error?: string;
+ warnings?: string[];
+ events: { seq: number; ts: string; kind: "auth" | "token" | "state"; line: string }[];
+ }
+ | { error: string };
+export type PostApiTauriRemoteAccessTunnelResponse =
+ | {
+ version: number;
+ enabled: false | true;
+ state: "error" | "stopped" | "listening";
+ listening: false | true;
+ listen: { address: string; port: number };
+ port: number;
+ auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };
+ addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];
+ recommended?: string;
+ link?: string;
+ maskLink?: string;
+ qr?: string;
+ linkSource?: "loopback" | "lan";
+ pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };
+ generatedPassword?: string;
+ tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };
+ localPort?: number;
+ error?: string;
+ warnings?: string[];
+ events: { seq: number; ts: string; kind: "auth" | "token" | "state"; line: string }[];
+ }
+ | { error: string };
+export type DeleteApiTauriRemoteAccessTunnelResponse =
+ | {
+ version: number;
+ enabled: false | true;
+ state: "error" | "stopped" | "listening";
+ listening: false | true;
+ listen: { address: string; port: number };
+ port: number;
+ auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };
+ addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];
+ recommended?: string;
+ link?: string;
+ maskLink?: string;
+ qr?: string;
+ linkSource?: "loopback" | "lan";
+ pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };
+ generatedPassword?: string;
+ tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };
+ localPort?: number;
+ error?: string;
+ warnings?: string[];
+ events: { seq: number; ts: string; kind: "auth" | "token" | "state"; line: string }[];
+ }
+ | { error: string };
+
+export interface PostApiTauriRemoteSettingsBody {
+ enabled?: false | true;
+}
+export interface PostApiTauriRemoteMachinesBody {
+ machineId?: string;
+ row?: { name?: string; host?: string; port?: number; user?: string; remotePort?: number; profileName?: string; startCommand?: string; color?: string; tintBorder?: false | true };
+ secrets?: { password?: string; passphrase?: string };
+}
+export interface DeleteApiTauriRemoteMachinesBody {
+ machineId?: string;
+}
+export interface PostApiTauriRemoteMachinesTestBody {
+ machineId?: string;
+}
+export interface PostApiTauriRemoteMachinesConnectBody {
+ machineId?: string;
+}
+export interface PostApiTauriRemoteMachinesDisconnectBody {
+ machineId?: string;
+}
+export interface PostApiTauriRemoteMachinesInstallBody {
+ machineId?: string;
+}
+export interface PostApiTauriRemoteSyncApplyBody {
+ machineId?: string;
+ plugins?: { name?: string; spec?: string }[];
+ skills?: { name?: string; root?: string }[];
+}
+export interface PostApiTauriRemoteAccessBody {
+ enabled?: false | true;
+ address?: string;
+ port?: number;
+ authEnabled?: false | true;
+ scope?: "public_only" | "all";
+ password?: null | string;
+}
+export interface PostApiTauriRemoteAccessTunnelBody {
+ mode?: "quick" | "token";
+ token?: string;
+ hostname?: string;
+}
+export interface GetApiTauriRemoteMachinesEventsQuery {
+ machineId?: GetApiTauriRemoteMachinesEventsQueryMachineId;
+ sinceSeq?: GetApiTauriRemoteMachinesEventsQuerySinceSeq;
+}
+export interface GetApiTauriRemoteAccessQuery {
+ sincePairingUseSeq?: GetApiTauriRemoteAccessQuerySincePairingUseSeq;
+}
diff --git a/packages/dsh-tauri-ssh/src/client/apis/parsers.test.ts b/packages/dsh-tauri-remote/src/client/apis/parsers.test.ts
similarity index 90%
rename from packages/dsh-tauri-ssh/src/client/apis/parsers.test.ts
rename to packages/dsh-tauri-remote/src/client/apis/parsers.test.ts
index deccae89..0b0e6a84 100644
--- a/packages/dsh-tauri-ssh/src/client/apis/parsers.test.ts
+++ b/packages/dsh-tauri-remote/src/client/apis/parsers.test.ts
@@ -9,6 +9,7 @@ import {
machineListOf,
savePayloadOf,
sessionRoleOf,
+ settingsWarningOf,
syncApplyResultOf,
syncPreviewOf,
testResultOf,
@@ -236,12 +237,39 @@ describe('enabledOf', () => {
})
})
+describe('settingsWarningOf', () => {
+ it('reads the migration warning and treats a missing or blank one as absent', () => {
+ expect(settingsWarningOf({ enabled: true, warning: 'machines.json 不是合法 JSON' })).toBe('machines.json 不是合法 JSON')
+ expect(settingsWarningOf({ enabled: true })).toBeNull()
+ expect(settingsWarningOf({ enabled: true, warning: '' })).toBeNull()
+ expect(settingsWarningOf({ enabled: true, warning: 7 })).toBeNull()
+ expect(settingsWarningOf(undefined)).toBeNull()
+ })
+})
+
describe('sessionRoleOf', () => {
- it('reads the remote flag and the originating host', () => {
+ it('reads matching role and remote fields from the host', () => {
expect(sessionRoleOf({ role: 'remote', remote: true, origin: 'ops' })).toEqual({ remote: true, origin: 'ops' })
+ expect(sessionRoleOf({ role: 'remote', remote: true })).toEqual({ remote: true })
expect(sessionRoleOf({ role: 'local', remote: false })).toEqual({ remote: false })
- expect(sessionRoleOf(undefined)).toEqual({ remote: false })
- expect(sessionRoleOf({ remote: 'yes', origin: '' })).toEqual({ remote: false })
+ })
+
+ it.each([
+ undefined,
+ null,
+ [[]],
+ 'local',
+ {},
+ { remote: false },
+ { role: 'local' },
+ { role: 'local', remote: 'false' },
+ { role: 'local', remote: true },
+ { role: 'remote', remote: false },
+ { role: 'unknown', remote: false },
+ { role: 'local', remote: false, error: 'denied' },
+ { role: 'local', remote: false, origin: 7 },
+ ])('returns unknown for a malformed role response: %j', (value) => {
+ expect(sessionRoleOf(value)).toBeNull()
})
})
@@ -274,8 +302,8 @@ describe('installResultOf', () => {
describe('errorMessageOf', () => {
it('maps the missing-endpoint statuses to the stable transport code', () => {
- expect(errorMessageOf(new Error('请求失败 (405)'))).toBe('SSH_API_HTTP_405')
- expect(errorMessageOf(new Error('请求失败 (404)'))).toBe('SSH_API_HTTP_404')
+ expect(errorMessageOf(new Error('请求失败 (405)'))).toBe('REMOTE_API_HTTP_405')
+ expect(errorMessageOf(new Error('请求失败 (404)'))).toBe('REMOTE_API_HTTP_404')
})
it('keeps the host prose and the unknown transport failures', () => {
@@ -289,8 +317,8 @@ describe('errorMessageOf', () => {
describe('isTransportError', () => {
it('separates the transport codes from host-provided prose', () => {
- expect(isTransportError('SSH_API_HTTP_405')).toBe(true)
- expect(isTransportError('SSH_API_EMPTY')).toBe(true)
+ expect(isTransportError('REMOTE_API_HTTP_405')).toBe(true)
+ expect(isTransportError('REMOTE_API_EMPTY')).toBe(true)
expect(isTransportError('auth failed')).toBe(false)
})
})
diff --git a/packages/dsh-tauri-ssh/src/client/apis/parsers.ts b/packages/dsh-tauri-remote/src/client/apis/parsers.ts
similarity index 91%
rename from packages/dsh-tauri-ssh/src/client/apis/parsers.ts
rename to packages/dsh-tauri-remote/src/client/apis/parsers.ts
index 0ae29193..a3a04b2f 100644
--- a/packages/dsh-tauri-ssh/src/client/apis/parsers.ts
+++ b/packages/dsh-tauri-remote/src/client/apis/parsers.ts
@@ -4,20 +4,20 @@ import type {
MachineRow,
MachineStatus,
ProgressPhase,
+ RemoteMachineEvent,
SecretValues,
- SshMachineEvent,
SyncApplyResult,
SyncItemResult,
SyncPluginItem,
SyncPreview,
SyncSkillItem,
} from '../types/index'
-import type { PostApiTauriSshMachinesBody } from './index.type'
+import type { PostApiTauriRemoteMachinesBody } from './index.type'
import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
import { messageOf } from '../../shared/error'
import { isLifecycleState } from '../types/index'
-export const SSH_API_EMPTY = 'SSH_API_EMPTY'
+export const REMOTE_API_EMPTY = 'REMOTE_API_EMPTY'
const MISSING_API_STATUSES: readonly number[] = [404, 405]
const HTTP_FAILURE = /^请求失败 \((\d{3})\)(?:: )?/
@@ -41,7 +41,7 @@ function entriesOf(value: unknown): unknown[] {
}
export function isTransportError(message: string): boolean {
- return message.startsWith('SSH_API_')
+ return message.startsWith('REMOTE_API_')
}
export function errorMessageOf(error: unknown): string {
@@ -51,7 +51,7 @@ export function errorMessageOf(error: unknown): string {
return message
const status = Number(match[1])
if (MISSING_API_STATUSES.includes(status))
- return `SSH_API_HTTP_${status}`
+ return `REMOTE_API_HTTP_${status}`
return message.slice(match[0].length) || message
}
@@ -61,11 +61,18 @@ export function enabledOf(value: unknown): boolean | undefined {
return typeof value.enabled === 'boolean' ? value.enabled : undefined
}
-export function sessionRoleOf(value: unknown): { remote: boolean, origin?: string } {
- const source = isRecord(value) ? value : {}
- const origin = textOf(source.origin)
+export function settingsWarningOf(value: unknown): string | null {
+ return isRecord(value) ? textOf(value.warning) ?? null : null
+}
+
+export function sessionRoleOf(value: unknown): { remote: boolean, origin?: string } | null {
+ if (!isRecord(value) || value.error !== undefined || (value.origin !== undefined && typeof value.origin !== 'string'))
+ return null
+ if (!((value.role === 'local' && value.remote === false) || (value.role === 'remote' && value.remote === true)))
+ return null
+ const origin = textOf(value.origin)
return {
- remote: source.remote === true,
+ remote: value.remote,
...origin === undefined ? {} : { origin },
}
}
@@ -190,7 +197,7 @@ export function machineListOf(value: unknown): MachineListSnapshot {
}
}
-export function savePayloadOf(machine: MachineRow, secrets: SecretValues): PostApiTauriSshMachinesBody {
+export function savePayloadOf(machine: MachineRow, secrets: SecretValues): PostApiTauriRemoteMachinesBody {
const profileName = textOf(machine.profileName)?.trim() ?? ''
const startCommand = textOf(machine.startCommand)
const color = textOf(machine.color)
@@ -218,9 +225,9 @@ export function savePayloadOf(machine: MachineRow, secrets: SecretValues): PostA
}
}
-export function machineEventsOf(value: unknown): SshMachineEvent[] {
+export function machineEventsOf(value: unknown): RemoteMachineEvent[] {
const source = isRecord(value) ? value : {}
- const events: SshMachineEvent[] = []
+ const events: RemoteMachineEvent[] = []
for (const entry of entriesOf(source.items)) {
if (!isRecord(entry))
continue
diff --git a/packages/dsh-tauri-remote/src/client/components/access-section.test.tsx b/packages/dsh-tauri-remote/src/client/components/access-section.test.tsx
new file mode 100644
index 00000000..d50aa2f1
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/components/access-section.test.tsx
@@ -0,0 +1,405 @@
+// @vitest-environment jsdom
+import type { RemoteKey } from '../locales/index'
+import type { WireCall, WireReply } from '../test-utils/client-mock'
+import { fireEvent, screen, waitFor } from '@testing-library/dom'
+import { cleanup, render } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { en } from '../locales/index'
+import { store } from '../store/index'
+import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
+import { AccessSection } from './access-section'
+
+vi.mock('dsh-tauri-ui/client', async () => ({
+ ...(await import('../test-utils/ui-mock')).uiMock,
+ StateDot: ({ state }: { state: string }) => <span data-testid="state-dot" data-state={state} />,
+}))
+vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
+
+const t = ((key: string) => (en as Record<string, string>)[key] ?? key) as (key: RemoteKey) => string
+
+const BASE = '/api/tauri/remote/access'
+const TUNNEL = `${BASE}/tunnel`
+const TOKEN = `${BASE}/token`
+const LAN_SWITCH = en['access.lan.title']
+const TUNNEL_SWITCH = en['access.tunnel.title']
+const PERMANENT = '01234567'
+const MASKED = '••••••••'
+const REMOVED = [
+ 'access-auth-toggle',
+ 'access-auth-scope',
+ 'access-permanent-state',
+ 'access-permanent-copy',
+ 'access-pairing-copy',
+ 'access-pairing-link',
+ 'access-pairing-qr',
+ 'access-generated-password',
+ 'access-generated-password-value',
+ 'access-generated-password-dismiss',
+ 'access-logs-toggle',
+ 'access-events',
+ 'access-tunnel-events',
+]
+
+function authPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return { enabled: true, scope: 'all', hasPassword: false, hasToken: true, ...overrides }
+}
+
+function tunnelPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return { enabled: false, mode: 'quick', hostname: null, state: 'stopped', ...overrides }
+}
+
+function pairingPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return { code: 'AB12CD34', expiresAt: Date.now() + 300_000, ...overrides }
+}
+
+function statusPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ version: 1,
+ enabled: true,
+ state: 'listening',
+ listening: true,
+ listen: { address: '192.168.1.5', port: 3088 },
+ port: 3088,
+ auth: authPayload({ enabled: false, scope: 'public_only' }),
+ addresses: [{ address: '192.168.1.5', family: 'ipv4', interface: 'en0', scope: 'private', score: 120, recommended: true }],
+ recommended: '192.168.1.5',
+ tunnel: tunnelPayload(),
+ localPort: 3080,
+ events: [],
+ ...overrides,
+ }
+}
+
+function lanOff(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return statusPayload({ enabled: false, listening: false, state: 'stopped', ...overrides })
+}
+
+let queued: WireReply[] = []
+let route: (call: WireCall) => WireReply = () => replies.ok(statusPayload())
+
+function once(...next: WireReply[]): void {
+ queued.push(...next)
+}
+
+function getCalls(url: string, http: string): WireCall[] {
+ return sent.filter(call => call.url === url && call.http === http)
+}
+
+function lanSwitch(): HTMLElement {
+ return screen.getByRole('switch', { name: LAN_SWITCH })
+}
+
+beforeEach(() => {
+ resetWire()
+ store.access.reset()
+ queued = []
+ route = () => replies.ok(statusPayload())
+ answer(call => queued.shift() ?? route(call))
+})
+
+afterEach(() => {
+ cleanup()
+})
+
+describe('接入面板', () => {
+ it('首个快照到达前只显示加载态', async () => {
+ render(<AccessSection t={t} />)
+ expect(screen.getByTestId('access-section').textContent).toBe(en['access.loading'])
+ await screen.findByTestId('access-toggle')
+ })
+
+ it('拉取失败时显示 store 错误并停留在加载态', async () => {
+ route = () => replies.fail('连接被拒绝')
+ render(<AccessSection t={t} />)
+ expect((await screen.findByTestId('access-error')).textContent).toContain('连接被拒绝')
+ expect(screen.getByTestId('access-section').textContent).toContain(en['access.loading'])
+ })
+
+ it('面板顶部渲染 status.error 与 status.warnings', async () => {
+ route = () => replies.ok(statusPayload({ error: '监听端口被占用', warnings: ['地址会随网卡变化', '仅建议在可信网络使用'] }))
+ render(<AccessSection t={t} />)
+ expect((await screen.findByTestId('access-state-error')).textContent).toBe('监听端口被占用')
+ const lines = screen.getByTestId('access-warning').querySelectorAll('li')
+ expect(Array.from(lines).map(line => line.textContent)).toEqual(['地址会随网卡变化', '仅建议在可信网络使用'])
+ expect(screen.getByTestId('access-page-hint').textContent).toBe(en['access.page.hint'])
+ })
+
+ it('局域网关闭时只留开关这一行', async () => {
+ route = () => replies.ok(lanOff())
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-toggle')
+ expect(lanSwitch().getAttribute('aria-checked')).toBe('false')
+ expect(screen.queryByTestId('access-lan-address')).toBeNull()
+ expect(screen.queryByTestId('access-lan-draft')).toBeNull()
+ })
+
+ it('打开局域网开关提交固定认证参数', async () => {
+ once(replies.ok(lanOff()), replies.ok(statusPayload()))
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-toggle')
+ fireEvent.click(lanSwitch())
+ await waitFor(() => expect(sent.at(-1)?.body).toEqual({ enabled: true, authEnabled: true, scope: 'all' }))
+ expect(sent.at(-1)?.http).toBe('POST')
+ expect(sent.at(-1)?.url).toBe(BASE)
+ await screen.findByTestId('access-lan-address')
+ })
+
+ it('关闭局域网开关只提交 enabled: false', async () => {
+ once(replies.ok(statusPayload()), replies.ok(lanOff()))
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-lan-address')
+ fireEvent.click(lanSwitch())
+ await waitFor(() => expect(sent.at(-1)?.body).toEqual({ enabled: false }))
+ expect(sent.at(-1)?.http).toBe('POST')
+ await waitFor(() => expect(screen.queryByTestId('access-lan-address')).toBeNull())
+ })
+
+ it('地址下拉给出回环、全网卡与推荐地址,改动只落草稿', async () => {
+ once(replies.ok(statusPayload()), replies.ok(statusPayload({ listen: { address: '127.0.0.1', port: 3088 } })))
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-lan-address')
+ const select = screen.getByRole('combobox') as HTMLSelectElement
+ expect(Array.from(select.options).map(option => option.value)).toEqual(['127.0.0.1', '0.0.0.0', '192.168.1.5'])
+ expect(select.options[0]?.textContent).toBe(`127.0.0.1(${en['access.lan.loopback']})`)
+ expect(select.options[1]?.textContent).toBe(`0.0.0.0(${en['access.listen.allInterfaces']})`)
+ expect(select.options[2]?.textContent).toBe(`192.168.1.5 · en0(${en['access.listen.recommended']})`)
+ fireEvent.change(select, { target: { value: '127.0.0.1' } })
+ await screen.findByTestId('access-lan-draft')
+ expect(getCalls(BASE, 'POST')).toHaveLength(0)
+ fireEvent.click(screen.getByTestId('access-lan-cancel'))
+ await waitFor(() => expect(screen.queryByTestId('access-lan-draft')).toBeNull())
+ expect(getCalls(BASE, 'POST')).toHaveLength(0)
+ expect((screen.getByRole('combobox') as HTMLSelectElement).value).toBe('192.168.1.5')
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: '127.0.0.1' } })
+ fireEvent.click(await screen.findByTestId('access-lan-save'))
+ await waitFor(() => expect(getCalls(BASE, 'POST')).toHaveLength(1))
+ expect(getCalls(BASE, 'POST')[0]?.body).toEqual({ address: '127.0.0.1' })
+ await waitFor(() => expect(screen.queryByTestId('access-lan-draft')).toBeNull())
+ })
+
+ it('保存失败保留草稿输入并给出错误', async () => {
+ once(replies.ok(statusPayload()), replies.http(400))
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-lan-address')
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: '127.0.0.1' } })
+ fireEvent.click(await screen.findByTestId('access-lan-save'))
+ await waitFor(() => expect(screen.getByTestId('access-error').textContent).toContain('请求失败'))
+ expect(screen.getByTestId('access-lan-draft')).toBeTruthy()
+ expect((screen.getByRole('combobox') as HTMLSelectElement).value).toBe('127.0.0.1')
+ })
+
+ it('隧道关闭时不展开任何字段,打开开关本身不发请求', async () => {
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-tunnel-toggle')
+ expect(screen.queryByTestId('access-tunnel-mode')).toBeNull()
+ expect(screen.queryByTestId('access-tunnel-start')).toBeNull()
+ fireEvent.click(screen.getByRole('switch', { name: TUNNEL_SWITCH }))
+ await screen.findByTestId('access-tunnel-mode')
+ expect(screen.queryByTestId('access-tunnel-token')).toBeNull()
+ expect(screen.queryByTestId('access-tunnel-stop')).toBeNull()
+ expect(getCalls(TUNNEL, 'POST')).toHaveLength(0)
+ })
+
+ it('切到具名模式后按占位与主机名引导,缺 Token 时不提交', async () => {
+ route = () => replies.ok(statusPayload({ tunnel: tunnelPayload() }))
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-tunnel-toggle')
+ fireEvent.click(screen.getByRole('switch', { name: TUNNEL_SWITCH }))
+ await screen.findByTestId('access-tunnel-mode')
+ expect(screen.queryByTestId('access-tunnel-token')).toBeNull()
+ fireEvent.click(screen.getByRole('tab', { name: en['access.tunnel.mode.token'] }))
+ const tokenField = await screen.findByTestId('access-tunnel-token')
+ expect(screen.getByTestId('access-tunnel-hostname')).toBeTruthy()
+ expect(tokenField.getAttribute('placeholder')).toBe(en['access.tunnel.tokenPlaceholder'])
+ expect(screen.queryByTestId('access-tunnel-hint')).toBeNull()
+ expect((screen.getByTestId('access-tunnel-save') as HTMLButtonElement).disabled).toBe(true)
+ fireEvent.click(screen.getByTestId('access-tunnel-save'))
+ expect(getCalls(TUNNEL, 'POST')).toHaveLength(0)
+ fireEvent.change(tokenField, { target: { value: 'cf-new' } })
+ expect(screen.getByTestId('access-tunnel-hint').textContent).toBe(en['access.tunnel.hostnameRequired'])
+ fireEvent.change(screen.getByTestId('access-tunnel-hostname'), { target: { value: 'dsh.example.com' } })
+ expect(screen.queryByTestId('access-tunnel-hint')).toBeNull()
+ expect((screen.getByTestId('access-tunnel-save') as HTMLButtonElement).disabled).toBe(false)
+ })
+
+ it('quick 模式启动隧道:请求体只带模式', async () => {
+ once(
+ replies.ok(statusPayload({ tunnel: tunnelPayload() })),
+ replies.ok(statusPayload({ tunnel: tunnelPayload({ enabled: true, state: 'running', hostname: 'bold-fox-abc.trycloudflare.com' }) })),
+ )
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-tunnel-toggle')
+ fireEvent.click(screen.getByRole('switch', { name: TUNNEL_SWITCH }))
+ fireEvent.click(await screen.findByTestId('access-tunnel-start'))
+ await waitFor(() => expect(getCalls(TUNNEL, 'POST')).toHaveLength(1))
+ expect(getCalls(TUNNEL, 'POST')[0]?.body).toEqual({ mode: 'quick' })
+ await waitFor(() => expect(screen.getByTestId('access-tunnel-state').textContent).toBe(en['access.tunnel.state.running']))
+ })
+
+ it('具名模式沿用已保存 Token,只提交改动过的主机名', async () => {
+ once(
+ replies.ok(statusPayload({ tunnel: tunnelPayload({ enabled: true, mode: 'token', token: 'cf-saved', hostname: 'dsh.example.com' }) })),
+ replies.ok(statusPayload({ tunnel: tunnelPayload({ enabled: true, mode: 'token', token: 'cf-saved', hostname: 'new.example.com' }) })),
+ )
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-tunnel-hostname')
+ const token = screen.getByTestId('access-tunnel-token') as HTMLInputElement
+ expect(token.value).toBe('cf-saved')
+ expect(token.getAttribute('placeholder'), '已有 Token 时占位提示沿用').toBe(en['access.tunnel.tokenSaved'])
+ fireEvent.change(token, { target: { value: '' } })
+ expect(token.value, '清空 Token 输入必须回落到已保存凭据').toBe('cf-saved')
+ fireEvent.change(screen.getByTestId('access-tunnel-hostname'), { target: { value: 'new.example.com' } })
+ fireEvent.click(await screen.findByTestId('access-tunnel-save'))
+ await waitFor(() => expect(getCalls(TUNNEL, 'POST')).toHaveLength(1))
+ expect(getCalls(TUNNEL, 'POST')[0]?.body).toEqual({ mode: 'token', token: 'cf-saved', hostname: 'new.example.com' })
+ })
+
+ it('取消隧道草稿不发任何请求', async () => {
+ once(replies.ok(statusPayload({ tunnel: tunnelPayload({ enabled: true, mode: 'token', token: 'cf-saved', hostname: 'dsh.example.com' }) })))
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-tunnel-hostname')
+ fireEvent.change(screen.getByTestId('access-tunnel-hostname'), { target: { value: 'other.example.com' } })
+ fireEvent.click(await screen.findByTestId('access-tunnel-cancel'))
+ await waitFor(() => expect(screen.queryByTestId('access-tunnel-cancel')).toBeNull())
+ expect(getCalls(TUNNEL, 'POST')).toHaveLength(0)
+ expect(getCalls(TUNNEL, 'DELETE')).toHaveLength(0)
+ })
+
+ it('运行中的隧道停止走 DELETE', async () => {
+ once(
+ replies.ok(statusPayload({ tunnel: tunnelPayload({ enabled: true, state: 'running', hostname: 'bold-fox-abc.trycloudflare.com' }) })),
+ replies.ok(statusPayload({ tunnel: tunnelPayload({ enabled: true, state: 'stopped' }) })),
+ )
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-tunnel-stop')
+ expect((screen.getByTestId('access-tunnel-start') as HTMLButtonElement).disabled).toBe(true)
+ fireEvent.click(screen.getByTestId('access-tunnel-stop'))
+ await waitFor(() => expect(getCalls(TUNNEL, 'DELETE')).toHaveLength(1))
+ await waitFor(() => expect(screen.getByTestId('access-tunnel-state').textContent).toBe(en['access.tunnel.state.stopped']))
+ })
+
+ it('运行中的隧道只显示带绿点的状态,不再显示已就绪进度', async () => {
+ route = () => replies.ok(statusPayload({
+ tunnel: tunnelPayload({ enabled: true, state: 'running', progress: { stage: 'ready' } }),
+ }))
+ render(<AccessSection t={t} />)
+ const state = await screen.findByTestId('access-tunnel-state')
+ expect(state.textContent).toBe(en['access.tunnel.state.running'])
+ expect(state.firstElementChild?.getAttribute('data-state')).toBe('done')
+ expect(screen.queryByTestId('access-tunnel-progress')).toBeNull()
+ expect(screen.queryByText(en['access.tunnel.progress.ready'])).toBeNull()
+ })
+
+ it('隧道启动期按阶段显示进度:下载阶段带百分比', async () => {
+ route = () => replies.ok(statusPayload({
+ tunnel: tunnelPayload({ enabled: true, state: 'starting', progress: { stage: 'download', url: 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-arm64.tgz', received: 3_200_000, total: 6_400_000 } }),
+ }))
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-tunnel-progress')
+ expect(screen.getByTestId('access-tunnel-progress-line').textContent).toBe(`${en['access.tunnel.progress.download']} 50%`)
+ expect(screen.queryByTestId('state-dot')).toBeNull()
+ expect(screen.getByTestId('access-tunnel-progress-bar').querySelector('div')?.getAttribute('style')).toContain('width: 50%')
+ })
+
+ it('隧道失败时错误、重试与停止都可见', async () => {
+ route = () => replies.ok(statusPayload({
+ tunnel: tunnelPayload({ enabled: true, state: 'error', error: 'cloudflared 下载失败(已尝试:https://…)' }),
+ }))
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-tunnel-error')
+ expect(screen.getByTestId('access-tunnel-error').textContent).toContain('cloudflared 下载失败')
+ expect(screen.queryByTestId('state-dot')).toBeNull()
+ expect(screen.getByTestId('access-tunnel-start').textContent).toBe(en['access.tunnel.retry'])
+ expect((screen.getByTestId('access-tunnel-stop') as HTMLButtonElement).disabled).toBe(false)
+ })
+
+ it('没有配对码时提示开启监听,且不显示倒计时', async () => {
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-pairing')
+ expect(screen.getByTestId('access-pairing-code').textContent).toBe(en['access.pairing.none'])
+ expect(screen.queryByTestId('access-pairing-countdown')).toBeNull()
+ })
+
+ it('有配对码时显示码与剩余倒计时', async () => {
+ route = () => replies.ok(statusPayload({ pairing: pairingPayload() }))
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-pairing-countdown')
+ expect(screen.getByTestId('access-pairing-code').textContent).toBe('AB12CD34')
+ const countdown = screen.getByTestId('access-pairing-countdown').textContent ?? ''
+ expect(countdown.startsWith(`${en['access.pairing.remaining']} `)).toBe(true)
+ expect(countdown).toMatch(/\d:\d{2}$/)
+ expect(Array.from(screen.getByTestId('access-pairing').children, child => child.getAttribute('data-testid'))).toEqual(['access-pairing-countdown', 'access-pairing-code'])
+ expect(screen.getByTestId('access-pairing-code').className).toContain('border-l-[0.5px]')
+ })
+
+ it('配对码过期后提示已过期并自动刷新一次', async () => {
+ let expired = true
+ route = () => replies.ok(statusPayload(expired ? { pairing: pairingPayload({ expiresAt: Date.now() - 60_000 }) } : {}))
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-pairing-countdown')
+ expect(screen.getByTestId('access-pairing-countdown').textContent).toBe(en['access.pairing.expired'])
+ expired = false
+ await waitFor(() => expect(getCalls(BASE, 'GET').length).toBeGreaterThanOrEqual(2))
+ })
+
+ it('永久码未签发时只给生成按钮,生成后当次明文可见并走 POST /access/token', async () => {
+ once(replies.ok(statusPayload()), replies.ok(statusPayload({ auth: authPayload({ token: PERMANENT }) })))
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-token-rotate')
+ expect(screen.getByTestId('access-token-rotate').textContent).toBe(en['access.token.generate'])
+ expect(screen.queryByTestId('access-permanent-value')).toBeNull()
+ expect(screen.queryByTestId('access-permanent-reveal')).toBeNull()
+ expect(screen.queryByTestId('access-token-revoke')).toBeNull()
+ fireEvent.click(screen.getByTestId('access-token-rotate'))
+ await waitFor(() => expect(getCalls(TOKEN, 'POST')).toHaveLength(1))
+ await screen.findByTestId('access-permanent-value')
+ expect(screen.getByTestId('access-permanent-value').textContent).toBe(PERMANENT)
+ fireEvent.click(screen.getByTestId('access-permanent-reveal'))
+ await waitFor(() => expect(screen.getByTestId('access-permanent-value').textContent).toBe(MASKED))
+ })
+
+ it('永久码默认掩码、点显示才出明文,作废走 DELETE', async () => {
+ once(
+ replies.ok(statusPayload({ auth: authPayload({ token: PERMANENT }) })),
+ replies.ok(statusPayload({ auth: authPayload() })),
+ )
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-permanent-value')
+ expect(screen.getByTestId('access-permanent-value').textContent).toBe(MASKED)
+ const reveal = screen.getByTestId('access-permanent-reveal')
+ expect(reveal.textContent).toBe(en['access.token.reveal'])
+ expect(reveal.getAttribute('aria-pressed')).toBe('false')
+ expect(Array.from(screen.getByTestId('access-permanent').children, child => child.getAttribute('data-testid'))).toEqual(['access-token-revoke', 'access-permanent-reveal', 'access-permanent-value'])
+ expect(screen.getByTestId('access-permanent-value').className).toContain('border-l-[0.5px]')
+ fireEvent.click(reveal)
+ await waitFor(() => expect(screen.getByTestId('access-permanent-value').textContent).toBe(PERMANENT))
+ const hide = screen.getByTestId('access-permanent-reveal')
+ expect(hide.textContent).toBe(en['access.token.hide'])
+ expect(hide.getAttribute('aria-pressed')).toBe('true')
+ fireEvent.click(hide)
+ await waitFor(() => expect(screen.getByTestId('access-permanent-value').textContent).toBe(MASKED))
+ fireEvent.click(screen.getByTestId('access-token-revoke'))
+ await waitFor(() => expect(getCalls(TOKEN, 'DELETE')).toHaveLength(1))
+ await screen.findByTestId('access-token-rotate')
+ })
+
+ it('面板不再渲染二维码、隧道事件、最近事件与认证配置', async () => {
+ route = () => replies.ok(statusPayload({
+ qr: 'data:image/png;base64,QUJD',
+ pairing: pairingPayload({ qr: 'data:image/png;base64,QUJD' }),
+ tunnel: tunnelPayload({
+ enabled: true,
+ state: 'running',
+ hostname: 'bold-fox-abc.trycloudflare.com',
+ qr: 'data:image/png;base64,QUJD',
+ events: [{ seq: 1, ts: '2026-10-06T00:00:01.000Z', kind: 'state', line: '公网隧道已就绪' }],
+ }),
+ events: [{ seq: 1, ts: '2026-10-06T00:00:00.000Z', kind: 'state', line: '入站暴露已监听 192.168.1.5:3088' }],
+ }))
+ render(<AccessSection t={t} />)
+ await screen.findByTestId('access-pairing-code')
+ expect(document.querySelector('img')).toBeNull()
+ for (const id of REMOVED)
+ expect(screen.queryByTestId(id), `不应再渲染 ${id}`).toBeNull()
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/client/components/access-section.tsx b/packages/dsh-tauri-remote/src/client/components/access-section.tsx
new file mode 100644
index 00000000..6a09a405
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/components/access-section.tsx
@@ -0,0 +1,346 @@
+import type { ReactElement, ReactNode } from 'react'
+import type { RemoteKey } from '../locales/index'
+import type { AccessStatus, AccessTunnel, TunnelProgress } from '../types/index'
+import type { TunnelDraft } from '../utils/access-form'
+import { Button, Input, SegmentedControl, Select, StateDot, Switch } from 'dsh-tauri-ui/client'
+import { useStore } from 'dsh-tauri/client'
+import { useEffect, useRef, useState } from 'react'
+import * as service from '../service/access'
+import { store } from '../store/index'
+import { countdownOf, lanDirtyOf, tunnelBodyOf, tunnelDirtyOf, tunnelDraftOf, tunnelMissingOf } from '../utils/access-form'
+
+interface AccessSectionProps {
+ t: (key: RemoteKey) => string
+}
+
+const LOOPBACK = '127.0.0.1'
+const WILDCARD = '0.0.0.0'
+const LOOPBACK_ALIASES = [LOOPBACK, '::1', 'localhost']
+
+function tunnelKeyOf(tunnel: AccessTunnel): RemoteKey {
+ if (tunnel.state === 'error' || tunnel.error !== undefined)
+ return 'access.tunnel.state.error'
+ if (tunnel.state === 'starting')
+ return 'access.tunnel.state.starting'
+ return tunnel.state === 'running' ? 'access.tunnel.state.running' : 'access.tunnel.state.stopped'
+}
+
+function progressKeyOf(progress: TunnelProgress): RemoteKey {
+ return `access.tunnel.progress.${progress.stage}` as RemoteKey
+}
+
+function progressPercentOf(progress: TunnelProgress): number | null {
+ if (progress.stage !== 'download' || progress.received === undefined || progress.total === undefined || progress.total <= 0)
+ return null
+ return Math.min(100, Math.round((progress.received / progress.total) * 100))
+}
+
+function addressOptionsOf(status: AccessStatus, t: (key: RemoteKey) => string): { value: string, label: string }[] {
+ const extra = status.addresses
+ .filter(item => !LOOPBACK_ALIASES.includes(item.address) && item.address !== WILDCARD)
+ .map(item => ({
+ value: item.address,
+ label: `${item.address} · ${item.interface}${item.recommended ? `(${t('access.listen.recommended')})` : ''}`,
+ }))
+ return [
+ { value: LOOPBACK, label: `${LOOPBACK}(${t('access.lan.loopback')})` },
+ { value: WILDCARD, label: `${WILDCARD}(${t('access.listen.allInterfaces')})` },
+ ...extra,
+ ]
+}
+
+function Card({ children }: { children: ReactNode }): ReactElement {
+ return (
+ <section className="rounded-[12px] border-[0.5px] border-border-l2 bg-layer-1 px-[16px]">
+ <div className="flex flex-col">{children}</div>
+ </section>
+ )
+}
+
+function Row({ title, hint, children }: { title: string, hint?: string, children: ReactNode }): ReactElement {
+ return (
+ <div className="flex items-center justify-between gap-[24px] py-[16px] border-b-[0.5px] border-border-l2 last:border-b-0">
+ <div className="flex min-w-0 flex-col">
+ <span className="text-[14px] leading-[20px] text-primary">{title}</span>
+ {hint === undefined ? null : <span className="mt-[4px] text-[12px] leading-[18px] text-secondary">{hint}</span>}
+ </div>
+ <div className="flex flex-none flex-wrap items-center justify-end gap-[8px]">{children}</div>
+ </div>
+ )
+}
+
+export function AccessSection({ t }: AccessSectionProps): ReactElement {
+ const state = useStore(store.access)
+ const status = state.snapshot
+ const [now, setNow] = useState(() => Date.now())
+ const [lanDraft, setLanDraft] = useState<{ address: string } | null>(null)
+ const [tunnelDraft, setTunnelDraft] = useState<TunnelDraft | null>(null)
+ const [revealed, setRevealed] = useState(false)
+ const expiredRef = useRef(0)
+ const pairingExpiry = status?.pairing?.expiresAt
+
+ useEffect(() => {
+ void service.load()
+ }, [])
+
+ useEffect(() => {
+ if (pairingExpiry === undefined)
+ return
+ const timer = setInterval(() => setNow(Date.now()), 1000)
+ return () => clearInterval(timer)
+ }, [pairingExpiry])
+
+ useEffect(() => {
+ if (pairingExpiry === undefined || pairingExpiry > now || expiredRef.current === pairingExpiry)
+ return
+ expiredRef.current = pairingExpiry
+ void service.refresh()
+ }, [pairingExpiry, now])
+
+ if (status === null) {
+ return (
+ <div className="flex flex-col gap-[8px] text-[13px] leading-[20px] text-secondary" data-testid="access-section">
+ <span>{t('access.loading')}</span>
+ {state.error === null
+ ? null
+ : <span className="text-error" role="alert" data-testid="access-error">{state.error}</span>}
+ </div>
+ )
+ }
+
+ const tunnel = status.tunnel
+ const busy = state.busy
+ const address = lanDraft?.address ?? status.listen.address
+ const dirtyLan = lanDirtyOf(lanDraft, status.listen)
+ const tunnelForm = tunnelDraft ?? tunnelDraftOf(tunnel)
+ const tunnelOpen = tunnel.enabled || tunnelDraft !== null
+ const dirtyTunnel = tunnelDirtyOf(tunnelDraft, tunnel)
+ const missing = tunnelMissingOf(tunnelForm)
+ const tunnelLive = tunnel.enabled && (tunnel.state === 'running' || tunnel.state === 'starting')
+ const token = status.auth.token
+ const pairing = status.pairing
+ const countdown = pairing === undefined ? '' : countdownOf(pairing.expiresAt, now)
+ const progressPercent = tunnel.progress === undefined ? null : progressPercentOf(tunnel.progress)
+
+ async function setExposure(next: boolean): Promise<void> {
+ await service.apply(next ? { enabled: true, authEnabled: true, scope: 'all' } : { enabled: false })
+ }
+
+ async function saveLan(): Promise<void> {
+ if (lanDraft === null)
+ return
+ const result = await service.apply({ address: lanDraft.address })
+ if (result.ok)
+ setLanDraft(null)
+ }
+
+ async function setTunnelEnabled(next: boolean): Promise<void> {
+ if (next) {
+ setTunnelDraft(tunnelDraftOf(tunnel))
+ return
+ }
+ setTunnelDraft(null)
+ if (tunnel.enabled)
+ await service.stopTunnel()
+ }
+
+ function editTunnel(patch: Partial<TunnelDraft>): void {
+ setTunnelDraft(previous => ({ ...(previous ?? tunnelDraftOf(tunnel)), ...patch }))
+ }
+
+ async function submitTunnel(draft: TunnelDraft, saved: AccessTunnel): Promise<void> {
+ if (tunnelMissingOf(draft) !== undefined)
+ return
+ const body = tunnelBodyOf(draft)
+ const result = await service.startTunnel({
+ mode: body.mode,
+ token: body.token ?? saved.token,
+ hostname: body.hostname ?? saved.hostname ?? undefined,
+ })
+ if (result.ok)
+ setTunnelDraft(null)
+ }
+
+ function issueToken(): void {
+ setRevealed(true)
+ void service.rotateToken()
+ }
+
+ function revokeToken(): void {
+ setRevealed(false)
+ void service.revokeToken()
+ }
+
+ return (
+ <div className="flex flex-col gap-[16px] text-primary" data-testid="access-section">
+ {state.error === null
+ ? null
+ : <div className="text-[12px] leading-[18px] text-error" role="alert" data-testid="access-error">{state.error}</div>}
+ {status.error === undefined
+ ? null
+ : <div className="text-[12px] leading-[18px] text-error" data-testid="access-state-error">{status.error}</div>}
+ {status.warnings === undefined || status.warnings.length === 0
+ ? null
+ : <ul className="m-0 flex list-none flex-col gap-[4px] p-0 text-[12px] leading-[18px] text-warn" data-testid="access-warning">{status.warnings.map(line => <li key={line}>{line}</li>)}</ul>}
+
+ <div className="text-[12px] leading-[18px] text-secondary" data-testid="access-page-hint">{t('access.page.hint')}</div>
+
+ <Card>
+ <Row title={t('access.lan.title')} hint={t('access.lan.hint')}>
+ <span className="inline-flex" data-testid="access-toggle">
+ <Switch checked={status.enabled} label={t('access.lan.title')} disabled={busy} onChange={(next) => { void setExposure(next) }} />
+ </span>
+ </Row>
+ {status.enabled
+ ? (
+ <>
+ <Row title={t('access.listen.address')} hint={t('access.lan.addressHint')}>
+ <div data-testid="access-lan-address">
+ <Select options={addressOptionsOf(status, t)} value={address} label={t('access.listen.address')} disabled={busy} onChange={next => setLanDraft({ address: next })} />
+ </div>
+ </Row>
+ {dirtyLan
+ ? (
+ <div className="flex items-center justify-end gap-[24px] border-b-[0.5px] border-border-l2 py-[12px]" data-testid="access-lan-draft">
+ <div className="flex flex-none items-center gap-[8px]">
+ <Button variant="outline" size="sm" data-testid="access-lan-cancel" disabled={busy} onClick={() => setLanDraft(null)}>{t('access.draft.cancel')}</Button>
+ <Button variant="primary" size="sm" data-testid="access-lan-save" disabled={busy} onClick={() => { void saveLan() }}>{t('access.draft.save')}</Button>
+ </div>
+ </div>
+ )
+ : null}
+ </>
+ )
+ : null}
+ </Card>
+
+ <Card>
+ <Row title={t('access.tunnel.title')} hint={t('access.tunnel.intro')}>
+ <span className="inline-flex" data-testid="access-tunnel-toggle">
+ <Switch checked={tunnelOpen} label={t('access.tunnel.title')} disabled={busy} onChange={(next) => { void setTunnelEnabled(next) }} />
+ </span>
+ </Row>
+ {tunnelOpen
+ ? (
+ <>
+ <Row title={t('access.tunnel.mode')} hint={t('access.tunnel.modeHint')}>
+ <div data-testid="access-tunnel-mode">
+ <SegmentedControl
+ id="dsh-tauri-remote-access-tunnel-mode"
+ label={t('access.tunnel.mode')}
+ options={[{ value: 'quick', label: t('access.tunnel.mode.quick') }, { value: 'token', label: t('access.tunnel.mode.token') }]}
+ value={tunnelForm.mode}
+ disabled={busy}
+ onChange={(next) => { editTunnel({ mode: next === 'token' ? 'token' : 'quick' }) }}
+ />
+ </div>
+ </Row>
+ {tunnelForm.mode === 'token'
+ ? (
+ <>
+ <Row title={t('access.tunnel.token')} hint={t('access.tunnel.tokenHint')}>
+ <Input
+ type="password"
+ name="tunnel-token"
+ autoComplete="off"
+ aria-label={t('access.tunnel.token')}
+ data-testid="access-tunnel-token"
+ placeholder={t(tunnel.token === null || tunnel.token === undefined || tunnel.token === '' ? 'access.tunnel.tokenPlaceholder' : 'access.tunnel.tokenSaved')}
+ value={tunnelForm.token ?? ''}
+ disabled={busy}
+ onChange={event => editTunnel({ token: event.target.value === '' ? (tunnel.token ?? null) : event.target.value })}
+ />
+ </Row>
+ <Row title={t('access.tunnel.hostname')} hint={t('access.tunnel.hostnameHint')}>
+ <Input
+ name="tunnel-hostname"
+ autoComplete="off"
+ aria-label={t('access.tunnel.hostname')}
+ data-testid="access-tunnel-hostname"
+ value={tunnelForm.hostname}
+ disabled={busy}
+ onChange={event => editTunnel({ hostname: event.target.value })}
+ />
+ </Row>
+ </>
+ )
+ : null}
+ {missing === 'hostname'
+ ? <div className="pt-[12px] pb-[12px] text-[12px] leading-[18px] text-warn" data-testid="access-tunnel-hint">{t('access.tunnel.hostnameRequired')}</div>
+ : null}
+ <Row title={t('access.tunnel.state')}>
+ <div className="flex flex-none items-center gap-[8px]" data-testid="access-tunnel-actions">
+ <span className="inline-flex items-center gap-[6px] text-[12px] leading-[18px] text-secondary" data-testid="access-tunnel-state">
+ {tunnelKeyOf(tunnel) === 'access.tunnel.state.running' ? <StateDot state="done" size={6} /> : null}
+ {t(tunnelKeyOf(tunnel))}
+ </span>
+ {dirtyTunnel
+ ? (
+ <>
+ <Button variant="outline" size="sm" data-testid="access-tunnel-cancel" disabled={busy} onClick={() => setTunnelDraft(null)}>{t('access.draft.cancel')}</Button>
+ <Button variant="primary" size="sm" data-testid="access-tunnel-save" disabled={busy || missing !== undefined} onClick={() => { void submitTunnel(tunnelForm, tunnel) }}>{t('access.draft.save')}</Button>
+ </>
+ )
+ : (
+ <>
+ <Button variant="outline" size="sm" data-testid="access-tunnel-start" disabled={busy || tunnelLive || missing !== undefined} onClick={() => { void submitTunnel(tunnelForm, tunnel) }}>{t(tunnel.state === 'error' ? 'access.tunnel.retry' : 'access.tunnel.start')}</Button>
+ {tunnelLive || tunnel.state === 'error'
+ ? <Button variant="ghost" size="sm" data-testid="access-tunnel-stop" disabled={busy} onClick={() => { void service.stopTunnel() }}>{t('access.tunnel.stop')}</Button>
+ : null}
+ </>
+ )}
+ </div>
+ </Row>
+ {tunnel.progress === undefined || tunnelKeyOf(tunnel) === 'access.tunnel.state.running'
+ ? null
+ : (
+ <div className="flex flex-col gap-[6px] pt-[12px] pb-[12px]" data-testid="access-tunnel-progress">
+ <span className="text-[12px] leading-[18px] text-secondary" data-testid="access-tunnel-progress-line">
+ {progressPercent === null ? t(progressKeyOf(tunnel.progress)) : `${t(progressKeyOf(tunnel.progress))} ${progressPercent}%`}
+ </span>
+ <div className="h-[6px] w-full overflow-hidden rounded-[3px] bg-layer-3" data-testid="access-tunnel-progress-bar">
+ <div className="h-full rounded-[3px] bg-brand transition-[width] duration-200" style={{ width: `${progressPercent ?? 0}%` }} />
+ </div>
+ </div>
+ )}
+ {tunnel.error === undefined
+ ? null
+ : <div className="pt-[12px] pb-[12px] text-[12px] leading-[18px] text-error" role="alert" data-testid="access-tunnel-error">{tunnel.error}</div>}
+ </>
+ )
+ : null}
+ </Card>
+
+ <Card>
+ <Row title={t('access.control.title')} hint={t('access.control.hint')}>{null}</Row>
+ <Row title={t('access.pairing.title')} hint={t('access.pairing.hint')}>
+ <div className="flex flex-none items-center gap-[8px]" data-testid="access-pairing">
+ {pairing === undefined
+ ? <span className="text-[12px] leading-[18px] text-secondary" data-testid="access-pairing-code">{t('access.pairing.none')}</span>
+ : (
+ <>
+ <span className="text-[12px] leading-[18px] text-secondary" data-testid="access-pairing-countdown">
+ {countdown === '' ? t('access.pairing.expired') : `${t('access.pairing.remaining')} ${countdown}`}
+ </span>
+ <code className="border-l-[0.5px] border-border-l2 pl-[8px] text-[14px] leading-[20px] tracking-[2px]" data-testid="access-pairing-code">{pairing.code}</code>
+ </>
+ )}
+ </div>
+ </Row>
+ <Row title={t('access.token.title')} hint={t('access.token.hint')}>
+ <div className="flex flex-none items-center gap-[8px]" data-testid="access-permanent">
+ {token === undefined
+ ? <Button variant="outline" size="sm" data-testid="access-token-rotate" disabled={busy} onClick={issueToken}>{t('access.token.generate')}</Button>
+ : (
+ <>
+ <Button variant="ghost" size="sm" data-testid="access-token-revoke" disabled={busy} onClick={revokeToken}>{t('access.token.revoke')}</Button>
+ <Button variant="outline" size="sm" data-testid="access-permanent-reveal" aria-pressed={revealed} aria-label={t(revealed ? 'access.token.hide' : 'access.token.reveal')} onClick={() => setRevealed(value => !value)}>{t(revealed ? 'access.token.hide' : 'access.token.reveal')}</Button>
+ <code className="border-l-[0.5px] border-border-l2 pl-[8px] text-[14px] leading-[20px] tracking-[2px]" data-testid="access-permanent-value">{revealed ? token : '••••••••'}</code>
+ </>
+ )}
+ </div>
+ </Row>
+ </Card>
+ </div>
+ )
+}
diff --git a/packages/dsh-tauri-ssh/src/client/components/machines-section.test.tsx b/packages/dsh-tauri-remote/src/client/components/machines-section.test.tsx
similarity index 98%
rename from packages/dsh-tauri-ssh/src/client/components/machines-section.test.tsx
rename to packages/dsh-tauri-remote/src/client/components/machines-section.test.tsx
index 67d230c5..3139b433 100644
--- a/packages/dsh-tauri-ssh/src/client/components/machines-section.test.tsx
+++ b/packages/dsh-tauri-remote/src/client/components/machines-section.test.tsx
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import type { SshKey } from '../locales/index'
+import type { RemoteKey } from '../locales/index'
import type { WireCall, WireReply } from '../test-utils/client-mock'
import type { MachineRow, RemoteBridge } from '../types/index'
import { fireEvent, screen, waitFor, within } from '@testing-library/dom'
@@ -12,7 +12,7 @@ import { store } from '../store/index'
import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
import { MachinesSection } from './machines-section'
-const baseURL = '/api/tauri/ssh'
+const baseURL = '/api/tauri/remote'
vi.mock('dsh-tauri-ui/client', async () => (await import('../test-utils/ui-mock')).uiMock)
vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
@@ -23,7 +23,7 @@ interface SavePayload {
secrets?: Record<string, unknown>
}
-const t = ((key: string) => (en as Record<string, string>)[key] ?? key) as (key: SshKey) => string
+const t = ((key: string) => (en as Record<string, string>)[key] ?? key) as (key: RemoteKey) => string
const unreachableBridge: RemoteBridge = {
probe: () => Promise.reject(new Error('NODE_NOT_ANSWERED: invoke remote_bridge_ping timed out')),
@@ -57,7 +57,9 @@ beforeEach(() => {
store.machines.reset()
queued = []
route = () => replies.ok({ items: [] })
- answer(call => queued.shift() ?? route(call))
+ answer(call => call.url === `${baseURL}/session/role`
+ ? replies.ok({ role: 'local', remote: false })
+ : queued.shift() ?? route(call))
})
afterEach(() => {
@@ -77,9 +79,10 @@ function mount(overrides: { value?: unknown, bridge?: RemoteBridge, route?: (cal
describe('machinesSection', () => {
it('renders the read-only SSH-in-progress banner on a remote target and hides management', async () => {
+ answer(call => route(call))
mount({
route: call => call.url === `${baseURL}/session/role`
- ? replies.ok({ remote: true, origin: 'ops' })
+ ? replies.ok({ role: 'remote', remote: true, origin: 'ops' })
: replies.ok({ items: [{ ...machineA, state: 'disconnected' }] }),
})
await waitFor(() => expect(screen.getByTestId('remote-session-banner')).toBeTruthy())
diff --git a/packages/dsh-tauri-ssh/src/client/components/machines-section.tsx b/packages/dsh-tauri-remote/src/client/components/machines-section.tsx
similarity index 94%
rename from packages/dsh-tauri-ssh/src/client/components/machines-section.tsx
rename to packages/dsh-tauri-remote/src/client/components/machines-section.tsx
index 83dac152..82eb009f 100644
--- a/packages/dsh-tauri-ssh/src/client/components/machines-section.tsx
+++ b/packages/dsh-tauri-remote/src/client/components/machines-section.tsx
@@ -1,5 +1,5 @@
import type { CSSProperties, ReactNode } from 'react'
-import type { SshKey } from '../locales/index'
+import type { RemoteKey } from '../locales/index'
import type { MachinesNotice } from '../store/modules/machines.types'
import type { InstallResult, MachineLifecycleState, MachineRow, MachineStatus, ProgressPhase, RemoteBridge, SecretValues } from '../types/index'
import { Button, Input, Modal, StateDot, Switch } from 'dsh-tauri-ui/client'
@@ -36,7 +36,7 @@ type DirtySecrets = Record<string, SecretValues>
type SecretFieldName = 'password' | 'passphrase'
interface MachinesSectionProps {
- t: (key: SshKey) => string
+ t: (key: RemoteKey) => string
bridge?: RemoteBridge | undefined
}
@@ -76,7 +76,7 @@ function RowShell({ id, name, tag, tintColor, tintBorder, status, trail, actions
status: MachineStatus | undefined
trail: readonly ProgressPhase[]
actions: ReactNode
- t: (key: SshKey) => string
+ t: (key: RemoteKey) => string
children?: ReactNode
}): ReactNode {
return (
@@ -105,7 +105,7 @@ function RowShell({ id, name, tag, tintColor, tintBorder, status, trail, actions
function EditPanel({ draft, t, hasPassword, hasPassphrase, dirty, saving, onChange, onSecret, onSave, onCancel }: {
draft: Draft
- t: (key: SshKey) => string
+ t: (key: RemoteKey) => string
hasPassword: boolean
hasPassphrase: boolean
dirty: SecretValues
@@ -165,7 +165,7 @@ function EditPanel({ draft, t, hasPassword, hasPassphrase, dirty, saving, onChan
function RowActions({ id, t, status, busy, bridgeOpen, bridgePending, opening, onTest, onConnect, onDisconnect, onOpen, extras }: {
id: string
- t: (key: SshKey) => string
+ t: (key: RemoteKey) => string
status: MachineStatus | undefined
busy: 'test' | 'connect' | 'disconnect' | 'install' | undefined
bridgeOpen: boolean
@@ -222,7 +222,7 @@ function RowDetails({ id, status, busy, logLines, bridgeError, installResult, t,
logLines: readonly string[]
bridgeError: string | undefined
installResult: InstallResult | undefined
- t: (key: SshKey) => string
+ t: (key: RemoteKey) => string
onInstall: (id: string) => void
}): ReactNode {
return (
@@ -271,7 +271,7 @@ function LogStream({ id, lines, fallback }: { id: string, lines: readonly string
function InstallPanel({ status, busy, t, onInstall }: {
status: MachineStatus
busy: 'test' | 'connect' | 'disconnect' | 'install' | undefined
- t: (key: SshKey) => string
+ t: (key: RemoteKey) => string
onInstall: () => void
}): ReactNode {
const installing = busy === 'install' || status.progress?.phase === 'installing'
@@ -292,7 +292,7 @@ function InstallPanel({ status, busy, t, onInstall }: {
)
}
-function installNoteOf(result: InstallResult, t: (key: SshKey) => string): string {
+function installNoteOf(result: InstallResult, t: (key: RemoteKey) => string): string {
if (result.credentialsError !== undefined) {
return t('install.done.error') + result.credentialsError
}
@@ -321,7 +321,7 @@ function Field({ label, span = 6, children }: { label: string, span?: FieldSpan,
function AppearanceEditor({ row, t, onChange, draftKey }: {
row: MachineRow
- t: (key: SshKey) => string
+ t: (key: RemoteKey) => string
onChange: (key: string, patch: Partial<MachineRow>) => void
draftKey: string
}): ReactNode {
@@ -370,7 +370,7 @@ function SecretField({ field, label, keyName, hasSecret, t, value, onValue }: {
label: string
keyName: string
hasSecret: boolean
- t: (key: SshKey) => string
+ t: (key: RemoteKey) => string
value: string
onValue: (key: string, field: SecretFieldName, value: string) => void
}): ReactNode {
@@ -391,7 +391,7 @@ function colorOf(row: MachineRow): string | undefined {
return row.color === undefined || row.color === '' ? undefined : row.color
}
-const STEP_KEY_OF: Record<ProgressPhase, SshKey> = {
+const STEP_KEY_OF: Record<ProgressPhase, RemoteKey> = {
handshake: 'step.handshake',
installing: 'step.installing',
starting: 'step.starting',
@@ -399,7 +399,7 @@ const STEP_KEY_OF: Record<ProgressPhase, SshKey> = {
syncing: 'step.syncing',
}
-function StepRail({ trail, t }: { trail: readonly ProgressPhase[], t: (key: SshKey) => string }): ReactNode {
+function StepRail({ trail, t }: { trail: readonly ProgressPhase[], t: (key: RemoteKey) => string }): ReactNode {
if (trail.length === 0)
return null
const current = trail[trail.length - 1]
@@ -427,7 +427,7 @@ function dotStateOf(status: MachineStatus | undefined): DotState {
return 'idle'
}
-const STATUS_KEY_OF: Record<MachineLifecycleState, SshKey> = {
+const STATUS_KEY_OF: Record<MachineLifecycleState, RemoteKey> = {
'disconnected': 'status.disconnected',
'testing': 'status.testing',
'connecting': 'status.connecting',
@@ -436,7 +436,7 @@ const STATUS_KEY_OF: Record<MachineLifecycleState, SshKey> = {
'given-up': 'status.givenUp',
}
-function statusTextOf(status: MachineStatus | undefined, t: (key: SshKey) => string): string {
+function statusTextOf(status: MachineStatus | undefined, t: (key: RemoteKey) => string): string {
const progress = status?.progress
if (progress !== undefined) {
return t(`progress.${progress.phase}`)
@@ -459,7 +459,7 @@ function numberOf(raw: string, fallback: number): number {
return raw !== '' && Number.isFinite(parsed) ? parsed : fallback
}
-function noticeTextOf(notice: MachinesNotice, t: (key: SshKey) => string): string {
+function noticeTextOf(notice: MachinesNotice, t: (key: RemoteKey) => string): string {
if (notice.kind === 'text')
return notice.text
let text = t(notice.key)
@@ -469,7 +469,7 @@ function noticeTextOf(notice: MachinesNotice, t: (key: SshKey) => string): strin
}
function AddMachineDialog({ t, saving, takenIds, onSubmit, onClose }: {
- t: (key: SshKey) => string
+ t: (key: RemoteKey) => string
saving: boolean
takenIds: ReadonlySet<string>
onSubmit: (row: MachineRow) => void
@@ -487,7 +487,7 @@ function AddMachineDialog({ t, saving, takenIds, onSubmit, onClose }: {
const slug = slugOf(host)
const effectiveId = idTouched ? id.trim() : (slug === '' ? '' : freeIdOf(slug, takenIds))
const trimmedHost = host.trim()
- const errorKey: SshKey | null
+ const errorKey: RemoteKey | null
= trimmedHost === ''
? 'add.host_required'
: !ID_PATTERN.test(effectiveId)
@@ -730,6 +730,36 @@ export function MachinesSection({ t, bridge = desktopBridge }: MachinesSectionPr
)
}
+ const enableRow = (
+ <div className="flex items-center justify-between gap-[24px] rounded-[12px] border-[0.5px] border-border-l2 bg-layer-1 px-[16px] py-[16px]">
+ <div className="flex min-w-0 flex-col">
+ <span className="text-[14px] leading-[20px] text-primary">{t('hero.title')}</span>
+ <span className="mt-[4px] text-[12px] leading-[18px] text-secondary">{t('enable.hint')}</span>
+ </div>
+ <span className="inline-flex" data-testid="machines-enable-toggle">
+ <Switch checked={state.enabled === true} label={t('hero.enable')} disabled={state.enabling} onChange={(next) => { void service.setEnabled(next) }} />
+ </span>
+ </div>
+ )
+
+ if (state.enabled === false) {
+ return (
+ <div className="flex flex-col gap-[12px] max-w-[960px] text-primary" data-testid="machines-section">
+ <h2 className="m-0 text-[18px] leading-[28px] font-semibold text-primary">{t('title')}</h2>
+ {enableRow}
+ {state.error === null
+ ? null
+ : (
+ <p className="m-0 text-[12px] leading-[18px] text-error" role="alert">
+ {t('error.banner')}
+ {errorTextOf(state.error, t)}
+ </p>
+ )}
+ <p className="m-0 rounded-[8px] border border-dashed border-border-l3 p-[12px] text-center text-[12px] leading-[18px] text-tertiary" data-testid="machines-disabled">{t('enable.off')}</p>
+ </div>
+ )
+ }
+
return (
<div className="flex flex-col gap-[12px] max-w-[960px] text-primary">
<div className="flex flex-wrap items-start justify-between gap-[12px]">
@@ -746,6 +776,7 @@ export function MachinesSection({ t, bridge = desktopBridge }: MachinesSectionPr
</Button>
</div>
</div>
+ {enableRow}
{state.notice !== null ? <p className="m-0 text-[12px] leading-[18px] text-secondary" data-testid="notice">{noticeTextOf(state.notice, t)}</p> : null}
{state.error !== null
? (
diff --git a/packages/dsh-tauri-remote/src/client/components/remote-section.test.tsx b/packages/dsh-tauri-remote/src/client/components/remote-section.test.tsx
new file mode 100644
index 00000000..34904c47
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/components/remote-section.test.tsx
@@ -0,0 +1,156 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { store } from '../store/index'
+import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
+import { RemoteSection } from './remote-section'
+
+const baseURL = '/api/tauri/remote'
+
+vi.mock('dsh-tauri-ui/client', async () => (await import('../test-utils/ui-mock')).uiMock)
+
+vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
+
+function accessPayload(): Record<string, unknown> {
+ return {
+ enabled: true,
+ listening: false,
+ state: 'stopped',
+ listen: { address: '127.0.0.1', port: 3088 },
+ port: 0,
+ addresses: [],
+ auth: { enabled: false, scope: 'public_only' },
+ tunnel: { enabled: false, mode: 'quick', hostname: null, state: 'stopped', events: [] },
+ events: [],
+ }
+}
+
+function bootWire(options: { enabled?: boolean, warning?: string } = {}) {
+ let enabled = options.enabled ?? false
+ answer((call) => {
+ if (call.url === `${baseURL}/settings` && call.http === 'GET') {
+ return replies.ok({
+ enabled,
+ ...options.warning === undefined ? {} : { warning: options.warning },
+ })
+ }
+ if (call.url === `${baseURL}/settings`) {
+ enabled = call.body.enabled === true
+ return replies.ok({ enabled })
+ }
+ if (call.url === `${baseURL}/session/role`)
+ return replies.ok({ remote: false })
+ if (call.url === `${baseURL}/access`)
+ return replies.ok(accessPayload())
+ return replies.ok({ items: [], discovered: [] })
+ })
+}
+
+const t = (key: string) => `t:${key}`
+
+beforeEach(() => {
+ resetWire()
+ store.machines.reset()
+ store.access.reset()
+})
+
+afterEach(() => {
+ cleanup()
+})
+
+describe('remoteSection', () => {
+ it('整页 Hero 与全局禁用按钮已移除:三个 Tabs 始终渲染', async () => {
+ bootWire()
+ render(<RemoteSection t={t as never} />)
+
+ await waitFor(() => expect(screen.getByTestId('remote-tabs')).toBeTruthy())
+ const tabs = within(screen.getByTestId('remote-tabs')).getAllByRole('tab')
+ expect(tabs.map(tab => tab.textContent)).toEqual(['t:tabs.access', 't:tabs.machines', 't:tabs.sync'])
+ expect(within(screen.getByTestId('remote-tabs')).getByRole('tab', { selected: true }).textContent).toBe('t:tabs.access')
+ expect(screen.queryByTestId('remote-hero')).toBeNull()
+ expect(screen.queryByTestId('remote-enable')).toBeNull()
+ expect(screen.queryByTestId('remote-hero-error')).toBeNull()
+ expect(screen.queryByRole('button', { name: 't:disable' })).toBeNull()
+ })
+
+ it('切换标签页渲染对应面板:已访问面板保持挂载,未访问面板不挂载', async () => {
+ bootWire({ enabled: true })
+ render(<RemoteSection t={t as never} />)
+ await waitFor(() => expect(screen.getByTestId('remote-tabs')).toBeTruthy())
+
+ expect(document.getElementById('dsh-tauri-remote-tabs-access-panel')?.hasAttribute('hidden')).toBe(false)
+ expect(document.getElementById('dsh-tauri-remote-tabs-sync-panel')).toBeNull()
+
+ fireEvent.click(within(screen.getByTestId('remote-tabs')).getByRole('tab', { name: 't:tabs.sync' }))
+ await waitFor(() => {
+ expect(document.getElementById('dsh-tauri-remote-tabs-sync-panel')?.hasAttribute('hidden')).toBe(false)
+ })
+ expect(document.getElementById('dsh-tauri-remote-tabs-access-panel')?.hasAttribute('hidden')).toBe(true)
+ })
+
+ it('开关搬进「连接到 SSH 服务器」Tab:关闭时给提示且不拉机器列表,打开后写设置并拉取', async () => {
+ bootWire()
+ render(<RemoteSection t={t as never} />)
+ await waitFor(() => expect(screen.getByTestId('remote-tabs')).toBeTruthy())
+
+ fireEvent.click(within(screen.getByTestId('remote-tabs')).getByRole('tab', { name: 't:tabs.machines' }))
+ const toggle = await screen.findByTestId('machines-enable-toggle')
+ expect(screen.getByTestId('machines-disabled')).toBeTruthy()
+ expect(sent.some(call => call.url === `${baseURL}/machines` && call.http === 'GET')).toBe(false)
+
+ fireEvent.click(within(toggle).getByRole('switch'))
+ await waitFor(() => expect(sent.some(call => call.url === `${baseURL}/settings` && call.http === 'POST')).toBe(true))
+ expect(sent.find(call => call.url === `${baseURL}/settings` && call.http === 'POST')?.body).toEqual({ enabled: true })
+ await waitFor(() => expect(store.machines.enabled).toBe(true))
+ await waitFor(() => expect(sent.some(call => call.url === `${baseURL}/machines` && call.http === 'GET')).toBe(true))
+ expect(screen.queryByTestId('machines-disabled')).toBeNull()
+ })
+
+ it('settings 读取失败不再挡住整个面板:Tabs 仍可选,开关落到关闭态', async () => {
+ answer(() => replies.http(405))
+ render(<RemoteSection t={t as never} />)
+
+ await waitFor(() => expect(screen.getByTestId('remote-tabs')).toBeTruthy())
+ await waitFor(() => expect(store.machines.enabled).toBe(false))
+ expect(screen.queryByTestId('remote-hero')).toBeNull()
+ })
+
+ it('迁移失败:settings 读接口带回的告警在面板上可见,且未启用时也能看到', async () => {
+ bootWire({ warning: 'machines.json 不是合法 JSON,已跳过' })
+ render(<RemoteSection t={t as never} />)
+
+ await waitFor(() => expect(screen.getByTestId('remote-migration-warning')).toBeTruthy())
+ expect(screen.getByTestId('remote-migration-warning').textContent).toBe('t:migration.warningmachines.json 不是合法 JSON,已跳过')
+ expect(screen.getByRole('alert').textContent).toContain('不是合法 JSON')
+ expect(screen.getByTestId('remote-tabs')).toBeTruthy()
+ })
+
+ it('迁移成功:settings 读接口不带 warning 时面板不渲染告警', async () => {
+ bootWire({ enabled: true })
+ render(<RemoteSection t={t as never} />)
+
+ await waitFor(() => expect(screen.getByTestId('remote-tabs')).toBeTruthy())
+ expect(screen.queryByTestId('remote-migration-warning')).toBeNull()
+ })
+
+ it('壳层 deep link:分区匹配时落到指定标签页,别的分区不动', async () => {
+ bootWire({ enabled: true })
+ render(<RemoteSection t={t as never} />)
+ await waitFor(() => expect(screen.getByTestId('remote-tabs')).toBeTruthy())
+
+ window.dispatchEvent(new MessageEvent('message', {
+ data: { type: 'dsh://settings:open', section: 'dsh-tauri-remote-sync', tab: 'sync' },
+ source: window,
+ }))
+ expect(within(screen.getByTestId('remote-tabs')).getByRole('tab', { selected: true }).textContent).toBe('t:tabs.access')
+
+ window.dispatchEvent(new MessageEvent('message', {
+ data: { type: 'dsh://settings:open', section: 'dsh-tauri-remote', tab: 'sync' },
+ source: window,
+ }))
+ await waitFor(() => {
+ expect(within(screen.getByTestId('remote-tabs')).getByRole('tab', { selected: true }).textContent).toBe('t:tabs.sync')
+ })
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/client/components/remote-section.tsx b/packages/dsh-tauri-remote/src/client/components/remote-section.tsx
new file mode 100644
index 00000000..35b01ac2
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/components/remote-section.tsx
@@ -0,0 +1,92 @@
+import type { ReactNode } from 'react'
+import type { RemoteKey } from '../locales/index'
+import { SegmentedControl } from 'dsh-tauri-ui/client'
+import { cn, useListenParent, useStore } from 'dsh-tauri/client'
+import { useEffect, useState } from 'react'
+import { REMOTE_TAB_ACCESS, REMOTE_TAB_MACHINES, REMOTE_TAB_SYNC, REMOTE_TABS_ID, SETTINGS_OPEN_MESSAGE, SETTINGS_SECTION_ID } from '../constants/index'
+import * as service from '../service/machines'
+import { store } from '../store/index'
+import { AccessSection } from './access-section'
+import { MachinesSection } from './machines-section'
+import { SyncPanel } from './sync-panel'
+
+type RemoteTab = typeof REMOTE_TAB_MACHINES | typeof REMOTE_TAB_SYNC | typeof REMOTE_TAB_ACCESS
+
+interface RemoteSectionProps {
+ t: (key: RemoteKey) => string
+}
+
+const TAB_KEYS: Record<RemoteTab, RemoteKey> = {
+ [REMOTE_TAB_MACHINES]: 'tabs.machines',
+ [REMOTE_TAB_SYNC]: 'tabs.sync',
+ [REMOTE_TAB_ACCESS]: 'tabs.access',
+}
+
+const TABS: RemoteTab[] = [REMOTE_TAB_ACCESS, REMOTE_TAB_MACHINES, REMOTE_TAB_SYNC]
+
+function MigrationWarning({ warning, t }: { warning: string, t: (key: RemoteKey) => string }): ReactNode {
+ return (
+ <p className="m-0 rounded-[8px] border border-dashed border-border-l3 px-[12px] py-[8px] text-[12px] leading-[19px] text-tertiary" role="alert" data-testid="remote-migration-warning">
+ {t('migration.warning')}
+ {warning}
+ </p>
+ )
+}
+
+export function RemoteSection({ t }: RemoteSectionProps): ReactNode {
+ const state = useStore(store.machines)
+ const [tab, setTab] = useState<RemoteTab>(REMOTE_TAB_ACCESS)
+ const [visited, setVisited] = useState<ReadonlySet<RemoteTab>>(() => new Set<RemoteTab>([REMOTE_TAB_ACCESS]))
+
+ function openTab(next: RemoteTab): void {
+ setTab(next)
+ setVisited(previous => previous.has(next) ? previous : new Set<RemoteTab>([...previous, next]))
+ }
+
+ useEffect(() => {
+ if (store.machines.enabled === null)
+ void service.loadSettings()
+ }, [])
+
+ useListenParent(SETTINGS_OPEN_MESSAGE, (message) => {
+ if (message.section !== SETTINGS_SECTION_ID)
+ return
+ if (message.tab === REMOTE_TAB_MACHINES || message.tab === REMOTE_TAB_SYNC || message.tab === REMOTE_TAB_ACCESS)
+ openTab(message.tab)
+ })
+
+ return (
+ <div className="flex flex-col gap-[12px] max-w-[960px] text-primary" data-testid="remote-section">
+ <div className="flex flex-wrap items-center justify-between gap-[12px]" data-testid="remote-tabs">
+ <SegmentedControl
+ id={REMOTE_TABS_ID}
+ label={t('nav')}
+ value={tab}
+ options={TABS.map(value => ({ value, label: t(TAB_KEYS[value]) }))}
+ onChange={(next) => {
+ if (next === REMOTE_TAB_MACHINES || next === REMOTE_TAB_SYNC || next === REMOTE_TAB_ACCESS)
+ openTab(next)
+ }}
+ />
+ </div>
+ {state.migrationWarning === null ? null : <MigrationWarning warning={state.migrationWarning} t={t} />}
+ {TABS.filter(value => value === tab || visited.has(value)).map((value) => {
+ const selected = value === tab
+ return (
+ <div
+ key={value}
+ id={`${REMOTE_TABS_ID}-${value}-panel`}
+ className={cn('min-w-0 flex-col gap-[12px]', selected ? 'flex' : 'hidden')}
+ role="tabpanel"
+ aria-labelledby={`${REMOTE_TABS_ID}-${value}`}
+ hidden={!selected}
+ >
+ {value === REMOTE_TAB_MACHINES
+ ? <MachinesSection t={t} />
+ : value === REMOTE_TAB_SYNC ? <SyncPanel t={t} /> : <AccessSection t={t} />}
+ </div>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/packages/dsh-tauri-ssh/src/client/components/sync-panel.test.tsx b/packages/dsh-tauri-remote/src/client/components/sync-panel.test.tsx
similarity index 98%
rename from packages/dsh-tauri-ssh/src/client/components/sync-panel.test.tsx
rename to packages/dsh-tauri-remote/src/client/components/sync-panel.test.tsx
index a2bcb857..d6df2262 100644
--- a/packages/dsh-tauri-ssh/src/client/components/sync-panel.test.tsx
+++ b/packages/dsh-tauri-remote/src/client/components/sync-panel.test.tsx
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import type { SshKey } from '../locales/index'
+import type { RemoteKey } from '../locales/index'
import type { MachineRow } from '../types/index'
import { fireEvent, screen, waitFor } from '@testing-library/dom'
import { cleanup, render } from '@testing-library/react'
@@ -10,7 +10,7 @@ import { store } from '../store/index'
import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
import { SyncPanel } from './sync-panel'
-const baseURL = '/api/tauri/ssh'
+const baseURL = '/api/tauri/remote'
vi.mock('dsh-tauri-ui/client', async () => (await import('../test-utils/ui-mock')).uiMock)
@@ -27,7 +27,7 @@ afterEach(() => {
vi.restoreAllMocks()
})
-const t = ((key: string) => (en as Record<string, string>)[key] ?? key) as (key: SshKey) => string
+const t = ((key: string) => (en as Record<string, string>)[key] ?? key) as (key: RemoteKey) => string
const regexOf = (text: string): RegExp => new RegExp(text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
@@ -225,7 +225,7 @@ describe('syncPanel', () => {
})
it('points a remote-session instance back at the initiating machine', async () => {
- routeWire({ [`${baseURL}/machines`]: { items: [] }, [`${baseURL}/session/role`]: { remote: true, origin: 'ops' } })
+ routeWire({ [`${baseURL}/machines`]: { items: [] }, [`${baseURL}/session/role`]: { role: 'remote', remote: true, origin: 'ops' } })
render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByTestId('sync-remote-note')).toBeTruthy())
expect(screen.getByTestId('sync-remote-note').textContent).toContain('Sync to remote')
diff --git a/packages/dsh-tauri-ssh/src/client/components/sync-panel.tsx b/packages/dsh-tauri-remote/src/client/components/sync-panel.tsx
similarity index 99%
rename from packages/dsh-tauri-ssh/src/client/components/sync-panel.tsx
rename to packages/dsh-tauri-remote/src/client/components/sync-panel.tsx
index 56be9375..f79905f8 100644
--- a/packages/dsh-tauri-ssh/src/client/components/sync-panel.tsx
+++ b/packages/dsh-tauri-remote/src/client/components/sync-panel.tsx
@@ -1,7 +1,7 @@
'use no memo'
import type { ReactNode } from 'react'
-import type { SshKey } from '../locales/index'
+import type { RemoteKey } from '../locales/index'
import type { SyncItemResult, SyncPluginItem, SyncSkillItem } from '../types/index'
import { Button, Pill, StateDot } from 'dsh-tauri-ui/client'
import { cn, useStore } from 'dsh-tauri/client'
@@ -13,7 +13,7 @@ import { syncKeyOf, toggleSelection } from '../store/modules/sync.utils'
import { errorTextOf } from '../utils/error'
interface SyncPanelProps {
- t: (key: SshKey) => string
+ t: (key: RemoteKey) => string
}
interface SelectableRow {
@@ -223,7 +223,7 @@ function SyncGroup({ label, empty, rows, selected, t, onToggle }: {
empty: string
rows: readonly SelectableRow[]
selected: ReadonlySet<string>
- t: (key: SshKey) => string
+ t: (key: RemoteKey) => string
onToggle: (key: string) => void
}): ReactNode {
const syncable = rows.filter(row => row.syncable)
@@ -281,7 +281,7 @@ function SyncGroup({ label, empty, rows, selected, t, onToggle }: {
function SyncResults({ results, applying, t, onRetry }: {
results: readonly SyncItemResult[]
applying: boolean
- t: (key: SshKey) => string
+ t: (key: RemoteKey) => string
onRetry: () => void
}): ReactNode {
const okCount = results.filter(item => item.ok).length
diff --git a/packages/dsh-tauri-remote/src/client/constants/index.test.ts b/packages/dsh-tauri-remote/src/client/constants/index.test.ts
new file mode 100644
index 00000000..58cd27fb
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/constants/index.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest'
+import { REMOTE_PLUGIN_NAME } from '../../shared/constants'
+import { LOCALE_EFFECT, PLUGIN_ID, POLL_EFFECT, REMOTE_TABS_ID, SECTION_EFFECT, SETTINGS_SECTION_ID } from './index'
+
+describe('client identity derivation', () => {
+ it('derives the settings section and locale namespace from the plugin name', () => {
+ expect(REMOTE_PLUGIN_NAME).toBe('dsh-tauri-remote')
+ expect(PLUGIN_ID).toBe(REMOTE_PLUGIN_NAME)
+ expect(SETTINGS_SECTION_ID).toBe(REMOTE_PLUGIN_NAME)
+ })
+
+ it('derives the tabs id and every effect label from the plugin name', () => {
+ expect(REMOTE_TABS_ID).toBe(`${REMOTE_PLUGIN_NAME}-tabs`)
+ expect([LOCALE_EFFECT, SECTION_EFFECT, POLL_EFFECT]).toEqual([
+ `${PLUGIN_ID}: locale`,
+ `${PLUGIN_ID}: settings section`,
+ `${PLUGIN_ID}: machine polling`,
+ ])
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/client/constants/index.ts b/packages/dsh-tauri-remote/src/client/constants/index.ts
new file mode 100644
index 00000000..b10d3752
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/constants/index.ts
@@ -0,0 +1,25 @@
+import { REMOTE_PLUGIN_NAME as PLUGIN_ID } from '../../shared/constants'
+
+export { REMOTE_PLUGIN_NAME as PLUGIN_ID } from '../../shared/constants'
+
+export const SETTINGS_SECTION_SLOT = 'settings.section'
+export const SETTINGS_SECTION_ID = PLUGIN_ID
+/**
+ * 分区顺序 50:排在核心分区(通用设置/模型/内置插件/Agent 预设)之后、其它插件分区之前。
+ * 不能取更小值:移动端设置弹窗以「首个分区」作为首屏详情页,语言切换项在通用设置里,
+ * 我们的分区一旦排最前,移动端首屏就会落到远程访问,`dsh-tauri-mobile-settings` 契约随之失败。
+ */
+export const SETTINGS_SECTION_ORDER = 50
+
+export const REMOTE_TAB_MACHINES = 'machines'
+export const REMOTE_TAB_SYNC = 'sync'
+export const REMOTE_TAB_ACCESS = 'access'
+export const REMOTE_TABS_ID = 'dsh-tauri-remote-tabs'
+export const SETTINGS_OPEN_MESSAGE = 'dsh://settings:open'
+
+export const REMOTE_BRIDGE_PING_COMMAND = 'remote_bridge_ping'
+export const REMOTE_OPEN_WINDOW_COMMAND = 'remote_open_window'
+
+export const LOCALE_EFFECT = `${PLUGIN_ID}: locale`
+export const SECTION_EFFECT = `${PLUGIN_ID}: settings section`
+export const POLL_EFFECT = `${PLUGIN_ID}: machine polling`
diff --git a/packages/dsh-tauri-remote/src/client/index.test.ts b/packages/dsh-tauri-remote/src/client/index.test.ts
new file mode 100644
index 00000000..ca7f8a5a
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/index.test.ts
@@ -0,0 +1,165 @@
+import type { ClientContext } from 'dsh-tauri/client'
+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'
+
+import { RemoteSection } from './components/remote-section.tsx'
+import { LOCALE_EFFECT, PLUGIN_ID, POLL_EFFECT, SECTION_EFFECT } from './constants/index'
+import { apply, inject, name } from './index'
+import { store } from './store/index'
+import { answer, replies, resetWire, sent } from './test-utils/client-mock'
+
+vi.mock('dsh-tauri/client', async () => {
+ const seam = await import('./test-utils/client-mock')
+ return {
+ ...seam.clientMock,
+ defineLocale: () => ({ NS: 'dsh-tauri-remote', text: (key: string) => `t:${key}`, registerLocale: () => () => {} }),
+ }
+})
+
+vi.mock('dsh-tauri-ui/client', () => ({}))
+
+interface ScriptedCtx {
+ ctx: ClientContext
+ slots: { inject: ReturnType<typeof vi.fn>, register: ReturnType<typeof vi.fn> }
+ effects: { run: (this: unknown) => unknown, label: string }[]
+}
+
+function scriptedCtx(): ScriptedCtx {
+ const slots = {
+ inject: vi.fn((_slot: string, _callback: () => unknown) => vi.fn()),
+ register: vi.fn(() => 'registration'),
+ }
+ const effects: { run: (this: unknown) => unknown, label: string }[] = []
+ const ctx = {
+ effect: (run: (this: unknown) => unknown, label: string) => { effects.push({ run, label }) },
+ get: () => undefined,
+ locale: {},
+ slots,
+ } as unknown as ClientContext
+ return { ctx, slots, effects }
+}
+
+function activateSection() {
+ const { ctx, slots, effects } = scriptedCtx()
+ apply(ctx)
+ const section = effects.find(entry => entry.label === SECTION_EFFECT)
+ expect(section).not.toBeUndefined()
+ const dispose = section!.run.call(ctx) as () => void
+ onTestFinished(dispose)
+ return { slots, dispose }
+}
+
+beforeEach(() => {
+ resetWire()
+ store.machines.reset()
+ vi.useFakeTimers()
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+describe('dsh-tauri-remote client plugin', () => {
+ it('declares its inject topology and its plugin name', () => {
+ expect(inject).toEqual(['slots', 'locale'])
+ expect(name).toBe(PLUGIN_ID)
+ })
+
+ it('registers three declarative effects on activation and does no eager work', () => {
+ const { ctx, slots, effects } = scriptedCtx()
+ apply(ctx)
+ expect(effects.map(entry => entry.label)).toEqual([LOCALE_EFFECT, SECTION_EFFECT, POLL_EFFECT])
+ for (const entry of effects)
+ expect(entry.run).toBeTypeOf('function')
+ expect(slots.inject).not.toHaveBeenCalled()
+ expect(slots.register).not.toHaveBeenCalled()
+ expect(sent).toEqual([])
+ })
+
+ it('registers the remote settings section only after a fresh local role confirmation', async () => {
+ store.machines.setRole({ remote: true, origin: 'old' })
+ let release!: (reply: ReturnType<typeof replies.ok>) => void
+ const pending = new Promise<ReturnType<typeof replies.ok>>((resolve) => {
+ release = resolve
+ })
+ answer(() => pending)
+ const { slots, dispose } = activateSection()
+ expect(slots.inject).not.toHaveBeenCalled()
+ expect(slots.register).not.toHaveBeenCalled()
+ expect(sent.map(call => call.url)).toEqual(['/api/tauri/remote/session/role'])
+
+ release(replies.ok({ role: 'local', remote: false }))
+ await vi.advanceTimersByTimeAsync(0)
+ expect(slots.inject).toHaveBeenCalledTimes(1)
+ 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?: unknown
+ }
+ expect(options.name).toBe('settings.section')
+ expect(options.id).toBe(PLUGIN_ID)
+ expect(options.order).toBe(50)
+ expect(options.label()).toBe('t:nav')
+ expect(options.locale).toBe(PLUGIN_ID)
+ expect(options.inject).toBeUndefined()
+ expect(slots.register.mock.calls[0][1]).toBe(RemoteSection)
+ expect(store.machines.role).toEqual({ remote: false })
+ dispose()
+ dispose()
+ expect(slots.inject.mock.results[0].value).toHaveBeenCalledTimes(1)
+ })
+
+ it.each([
+ replies.ok({ role: 'remote', remote: true, origin: 'ops' }),
+ replies.ok({}),
+ replies.ok({ remote: false }),
+ replies.ok({ role: 'local', remote: true }),
+ replies.ok({ role: 'remote', remote: false }),
+ replies.ok({ role: 'local', remote: false, error: 'denied' }),
+ replies.empty(),
+ replies.http(404),
+ replies.fail('denied', 403),
+ ])('never registers the section from a cached local role when the probe is not local: %j', async (reply) => {
+ store.machines.setRole({ remote: false })
+ answer(() => reply)
+ const { slots } = activateSection()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(slots.inject).not.toHaveBeenCalled()
+ expect(slots.register).not.toHaveBeenCalled()
+ expect(sent.map(call => call.url)).toEqual(['/api/tauri/remote/session/role'])
+ })
+
+ it('does not register the section when the role request throws', async () => {
+ store.machines.setRole({ remote: false })
+ answer(() => {
+ throw new Error('network offline')
+ })
+ const { slots } = activateSection()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(slots.inject).not.toHaveBeenCalled()
+ expect(slots.register).not.toHaveBeenCalled()
+ expect(sent.map(call => call.url)).toEqual(['/api/tauri/remote/session/role'])
+ })
+
+ it('does not register the section after disposal while a local role probe is pending', async () => {
+ let release!: (reply: ReturnType<typeof replies.ok>) => void
+ const pending = new Promise<ReturnType<typeof replies.ok>>((resolve) => {
+ release = resolve
+ })
+ answer(() => pending)
+ const { slots, dispose } = activateSection()
+ dispose()
+ release(replies.ok({ role: 'local', remote: false }))
+ await vi.advanceTimersByTimeAsync(0)
+ expect(slots.inject).not.toHaveBeenCalled()
+ expect(slots.register).not.toHaveBeenCalled()
+ expect(sent.map(call => call.url)).toEqual(['/api/tauri/remote/session/role'])
+ })
+})
diff --git a/packages/dsh-tauri-ssh/src/client/index.ts b/packages/dsh-tauri-remote/src/client/index.ts
similarity index 91%
rename from packages/dsh-tauri-ssh/src/client/index.ts
rename to packages/dsh-tauri-remote/src/client/index.ts
index a54a3ac0..b41a9d8a 100644
--- a/packages/dsh-tauri-ssh/src/client/index.ts
+++ b/packages/dsh-tauri-remote/src/client/index.ts
@@ -4,7 +4,7 @@ import { locale } from './locales/index'
import { pollFeature } from './register/poll'
import { sectionFeature } from './register/section'
-export type { SshKey } from './locales/index'
+export type { RemoteKey } from './locales/index'
export const name = PLUGIN_ID
diff --git a/packages/dsh-tauri-ssh/src/client/locales/index.test.ts b/packages/dsh-tauri-remote/src/client/locales/index.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/client/locales/index.test.ts
rename to packages/dsh-tauri-remote/src/client/locales/index.test.ts
diff --git a/packages/dsh-tauri-ssh/src/client/locales/index.ts b/packages/dsh-tauri-remote/src/client/locales/index.ts
similarity index 61%
rename from packages/dsh-tauri-ssh/src/client/locales/index.ts
rename to packages/dsh-tauri-remote/src/client/locales/index.ts
index 2c2cc8e6..ddd3c24b 100644
--- a/packages/dsh-tauri-ssh/src/client/locales/index.ts
+++ b/packages/dsh-tauri-remote/src/client/locales/index.ts
@@ -2,16 +2,18 @@ import { defineLocale } from 'dsh-tauri/client'
import { PLUGIN_ID } from '../constants/index'
export const zh = {
- 'nav': '服务器',
- 'tabs.machines': 'SSH 机器',
- 'tabs.sync': '同步到远端',
- 'hero.title': '远程机器',
- 'hero.desc': '把本机作为发起端,用 SSH 连接其他机器上的 dsh 实例:直连使用本机 ~/.ssh 的配置与密钥,可管理多台机器并一键切换、同步插件与 Skill。默认关闭,开启后才建立连接。',
- 'hero.enable': '启用 SSH',
+ 'nav': '远程访问',
+ 'tabs.machines': '连接 SSH',
+ 'tabs.sync': '同步远端',
+ 'hero.title': '远程访问',
+ 'hero.desc': '两个方向都由这里开通:用 SSH 连接其他机器上的 dsh 实例(直连使用本机 ~/.ssh 的配置与密钥),或把本机 dsh 暴露到局域网与公网隧道。默认关闭,开启后才建立连接或监听。',
+ 'hero.enable': '启用远程访问',
'hero.enabling': '正在启用…',
+ 'enable.hint': '打开后才会建立 SSH 连接、同步代码与暴露本机 dsh;开关只影响本机这个插件。',
+ 'enable.off': '已关闭:打开上面的开关后才能添加机器、同步或暴露本机。',
'disable': '禁用',
'error.unavailable': 'SSH 服务不可用:插件未加载或本地实例未就绪。',
- 'title': 'SSH 远程机器',
+ 'title': '连接到 SSH 服务器',
'intro': '连接直接使用本机 ~/.ssh 的配置与密钥:支持 config 别名、IdentityFile 与默认密钥;密码和私钥口令可选,仅在密钥不可用时作为回退。',
'loading': '加载中…',
'empty': '还没有 SSH 机器。点击「添加机器」创建第一台。',
@@ -32,6 +34,7 @@ export const zh = {
'secret.unset': '未设置',
'error.banner': '错误:',
'loadFailed': '面板数据加载失败。',
+ 'migration.warning': '旧状态目录迁移未完成,已按新目录空状态启动(旧文件未改动):',
'notice.connected': '已连接:{url}',
'notice.disconnected': '已断开',
'field.id': 'ID',
@@ -119,21 +122,76 @@ export const zh = {
'install.done.copied': '安装完成,已复制本机 API Key,正在自动连接…',
'install.done.nokey': '安装完成。本机未找到 DEEPSEEK_API_KEY,请在远端 dsh Web 的 Models 页面配置后使用。',
'install.done.error': '安装完成,但凭据复制失败:',
+ 'tabs.access': '远程访问',
+ 'access.loading': '正在读取暴露状态…',
+ 'access.page.hint': '同一网络或公网隧道访问本机,均需先通过认证。',
+ 'access.listen.address': '监听地址',
+ 'access.listen.allInterfaces': '全部网卡',
+ 'access.listen.recommended': '推荐',
+ 'access.tunnel.title': '公网隧道',
+ 'access.tunnel.progress.check': '检查 cloudflared',
+ 'access.tunnel.progress.download': '下载 cloudflared',
+ 'access.tunnel.progress.extract': '解压安装包',
+ 'access.tunnel.progress.verify': '校验可执行文件',
+ 'access.tunnel.progress.spawn': '启动进程',
+ 'access.tunnel.progress.domain': '等待分配域名',
+ 'access.tunnel.progress.ready': '隧道已就绪',
+ 'access.tunnel.intro': '把本机 dsh 通过 Cloudflare 隧道开放到公网,外网设备凭链接或配对码访问。',
+ 'access.tunnel.mode': '隧道模式',
+ 'access.tunnel.mode.quick': 'Quick(免账号)',
+ 'access.tunnel.mode.token': '具名(Token)',
+ 'access.tunnel.token': 'Tunnel Token',
+ 'access.tunnel.hostname': '公开主机名',
+ 'access.tunnel.start': '启动隧道',
+ 'access.tunnel.stop': '停止隧道',
+ 'access.tunnel.state.stopped': '隧道未运行',
+ 'access.tunnel.state.starting': '隧道启动中…',
+ 'access.tunnel.state.running': '隧道运行中',
+ 'access.tunnel.state.error': '隧道异常',
+ 'access.control.title': '访问控制',
+ 'access.control.hint': '打开局域网或隧道后,这里给出配对用的凭据。',
+ 'access.lan.title': '局域网',
+ 'access.lan.hint': '打开后同一网络的设备可访问本机 dsh;关闭时不监听。',
+ 'access.lan.addressHint': '推荐地址按可达性排序,「全部网卡」用于地址会变或多网卡的场景。',
+ 'access.lan.loopback': '仅本机',
+ 'access.draft.cancel': '取消',
+ 'access.draft.save': '保存',
+ 'access.tunnel.state': '隧道状态',
+ 'access.tunnel.modeHint': '免账号模式分配随机域名;具名模式用账号 Token 绑定自己的域名。',
+ 'access.tunnel.retry': '重试',
+ 'access.tunnel.tokenHint': 'Tunnel Token 由 Cloudflare 签发,用于把隧道绑定到你的账号。',
+ 'access.tunnel.tokenPlaceholder': '粘贴 Tunnel Token',
+ 'access.tunnel.tokenSaved': '已保存,留空沿用',
+ 'access.tunnel.hostnameHint': '在 Cloudflare 控制台把该主机名指向本机入口。',
+ 'access.tunnel.hostnameRequired': '具名模式需要公开主机名(例如 dsh.example.com)。',
+ 'access.pairing.title': '临时配对码',
+ 'access.pairing.hint': '设备输入配对连接,5 分钟内有效。',
+ 'access.pairing.none': '开启监听后这里会给出配对码。',
+ 'access.pairing.remaining': '剩余',
+ 'access.pairing.expired': '已过期,正在换新码…',
+ 'access.token.title': '永久访问码',
+ 'access.token.hint': '长期不变;泄露后可重新生成,旧码立即失效。',
+ 'access.token.generate': '生成',
+ 'access.token.revoke': '作废',
+ 'access.token.reveal': '显示',
+ 'access.token.hide': '隐藏',
} as const
-export type SshKey = keyof typeof zh
+export type RemoteKey = keyof typeof zh
export const en: Record<keyof typeof zh, string> = {
- 'nav': 'Service',
- 'tabs.machines': 'SSH machines',
+ 'nav': 'Remote access',
+ 'tabs.machines': 'Connect to SSH server',
'tabs.sync': 'Sync to remote',
- 'hero.title': 'Remote machines',
- 'hero.desc': 'Drive other machines\' dsh instances from this one over SSH: connections use this machine\'s ~/.ssh directly, and you can keep several machines, switch between them, and sync plugins and skills. Off by default — nothing connects until you enable it.',
- 'hero.enable': 'Enable SSH',
+ 'hero.title': 'Remote access',
+ 'hero.desc': 'Both directions start here: connect to dsh instances on other machines over SSH (using this machine\'s ~/.ssh directly), or expose this machine\'s dsh on your LAN and through a public tunnel. Off by default — nothing connects or listens until you enable it.',
+ 'hero.enable': 'Enable remote access',
'hero.enabling': 'Enabling…',
+ 'enable.hint': 'Turn this on to open SSH connections, sync code, and expose this machine; the switch only affects this plugin.',
+ 'enable.off': 'Off: turn the switch above on to add machines, sync, or expose this machine.',
'disable': 'Disable',
'error.unavailable': 'The SSH service is unavailable: the plugin is not loaded or the local instance is not ready.',
- 'title': 'SSH Remote Machines',
+ 'title': 'Connect to SSH server',
'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.',
@@ -154,6 +212,7 @@ export const en: Record<keyof typeof zh, string> = {
'secret.unset': 'not set',
'error.banner': 'Error: ',
'loadFailed': 'The panel failed to load.',
+ 'migration.warning': 'The legacy state directory was not fully migrated; starting from an empty new directory (legacy files untouched):',
'notice.connected': 'Connected: {url}',
'notice.disconnected': 'Disconnected',
'field.id': 'ID',
@@ -241,6 +300,59 @@ export const en: Record<keyof typeof zh, string> = {
'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: ',
+ 'tabs.access': 'Remote access',
+ 'access.loading': 'Reading exposure state…',
+ 'access.page.hint': 'Devices on the same network or through the public tunnel must authenticate first.',
+ 'access.listen.address': 'Listen address',
+ 'access.listen.allInterfaces': 'all interfaces',
+ 'access.listen.recommended': 'recommended',
+ 'access.tunnel.title': 'Public tunnel',
+ 'access.tunnel.progress.check': 'Checking cloudflared',
+ 'access.tunnel.progress.download': 'Downloading cloudflared',
+ 'access.tunnel.progress.extract': 'Extracting archive',
+ 'access.tunnel.progress.verify': 'Verifying binary',
+ 'access.tunnel.progress.spawn': 'Starting process',
+ 'access.tunnel.progress.domain': 'Waiting for an assigned hostname',
+ 'access.tunnel.progress.ready': 'Tunnel ready',
+ 'access.tunnel.intro': 'Opens this machine\u2019s dsh to the internet through a Cloudflare tunnel; other devices use the link or the pairing code.',
+ 'access.tunnel.mode': 'Tunnel mode',
+ 'access.tunnel.mode.quick': 'quick (no account)',
+ 'access.tunnel.mode.token': 'Named (token)',
+ 'access.tunnel.token': 'Tunnel token',
+ 'access.tunnel.hostname': 'Public hostname',
+ 'access.tunnel.start': 'Start tunnel',
+ 'access.tunnel.stop': 'Stop tunnel',
+ 'access.tunnel.state.stopped': 'Tunnel stopped',
+ 'access.tunnel.state.starting': 'Tunnel starting…',
+ 'access.tunnel.state.running': 'Tunnel running',
+ 'access.tunnel.state.error': 'Tunnel failed',
+ 'access.control.title': 'Access control',
+ 'access.control.hint': 'Pairing credentials appear here once the local network or tunnel is on.',
+ 'access.lan.title': 'Local network',
+ 'access.lan.hint': 'Turn this on to let devices on the same network reach this machine; off stops the listener.',
+ 'access.lan.addressHint': 'Recommended addresses are sorted by reachability; "all interfaces" suits multi-NIC hosts or addresses that change.',
+ 'access.lan.loopback': 'this machine only',
+ 'access.draft.cancel': 'Cancel',
+ 'access.draft.save': 'Save',
+ 'access.tunnel.state': 'Tunnel status',
+ 'access.tunnel.modeHint': 'The account-free mode assigns a random hostname; the named mode binds your own hostname with an account token.',
+ 'access.tunnel.retry': 'Retry',
+ 'access.tunnel.tokenHint': 'Issued by Cloudflare; it binds the tunnel to your account.',
+ 'access.tunnel.tokenPlaceholder': 'Paste the Tunnel token',
+ 'access.tunnel.tokenSaved': 'Saved — leave empty to keep it',
+ 'access.tunnel.hostnameHint': 'Point this hostname at the local entry in the Cloudflare dashboard.',
+ 'access.tunnel.hostnameRequired': 'Named mode needs a public hostname (for example dsh.example.com).',
+ 'access.pairing.title': 'Temporary pairing code',
+ 'access.pairing.hint': 'Enter this code on the other device; valid for 5 minutes.',
+ 'access.pairing.none': 'A pairing code appears here once listening is on.',
+ 'access.pairing.remaining': 'expires in',
+ 'access.pairing.expired': 'Expired, fetching a new code…',
+ 'access.token.title': 'Permanent access code',
+ 'access.token.hint': 'Does not rotate; regenerate it to invalidate the old code.',
+ 'access.token.generate': 'Generate',
+ 'access.token.revoke': 'Revoke',
+ 'access.token.reveal': 'Show',
+ 'access.token.hide': 'Hide',
}
export const locale = defineLocale(PLUGIN_ID, { zh, en })
diff --git a/packages/dsh-tauri-ssh/src/client/register/poll.test.ts b/packages/dsh-tauri-remote/src/client/register/poll.test.ts
similarity index 98%
rename from packages/dsh-tauri-ssh/src/client/register/poll.test.ts
rename to packages/dsh-tauri-remote/src/client/register/poll.test.ts
index 20526074..3273eee3 100644
--- a/packages/dsh-tauri-ssh/src/client/register/poll.test.ts
+++ b/packages/dsh-tauri-remote/src/client/register/poll.test.ts
@@ -6,7 +6,7 @@ import { store } from '../store/index'
import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
import { pollFeature } from './poll'
-const baseURL = '/api/tauri/ssh'
+const baseURL = '/api/tauri/remote'
vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
diff --git a/packages/dsh-tauri-ssh/src/client/register/poll.ts b/packages/dsh-tauri-remote/src/client/register/poll.ts
similarity index 56%
rename from packages/dsh-tauri-ssh/src/client/register/poll.ts
rename to packages/dsh-tauri-remote/src/client/register/poll.ts
index 1f01e298..ee76487d 100644
--- a/packages/dsh-tauri-ssh/src/client/register/poll.ts
+++ b/packages/dsh-tauri-remote/src/client/register/poll.ts
@@ -1,5 +1,6 @@
import type { MachineLifecycleState } from '../types/index'
import { defineRegister } from 'dsh-tauri/client'
+import { refresh as refreshAccess } from '../service/access'
import { poll } from '../service/machines'
import { store } from '../store/index'
@@ -12,10 +13,19 @@ function machinesInFlight(): boolean {
return Object.values(store.machines.statuses).some(status => ACTIVE_STATES.includes(status.state))
}
+/** 隧道从启动到拿到公网域名之间只有事件在动,面板需要跟着刷新;其余时刻靠操作回包更新。 */
+function tunnelStarting(): boolean {
+ const snapshot = store.access.snapshot
+ return snapshot !== null && !store.access.busy && snapshot.tunnel.state === 'starting'
+}
+
export const pollFeature = defineRegister((controller) => {
controller.interval(() => {
- if (controller.isDisposed() || !(machinesInFlight() || store.sync.applying))
+ if (controller.isDisposed())
return
- void poll()
+ if (tunnelStarting())
+ void refreshAccess()
+ if (machinesInFlight() || store.sync.applying)
+ void poll()
}, MACHINES_POLL_INTERVAL_MS)
})
diff --git a/packages/dsh-tauri-remote/src/client/register/section.ts b/packages/dsh-tauri-remote/src/client/register/section.ts
new file mode 100644
index 00000000..ba0e9b3e
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/register/section.ts
@@ -0,0 +1,20 @@
+import type { ClientContext } from 'dsh-tauri/client'
+import { defineRegister } from 'dsh-tauri/client'
+import { RemoteSection } from '../components/remote-section'
+import { SETTINGS_SECTION_ID, SETTINGS_SECTION_ORDER, SETTINGS_SECTION_SLOT } from '../constants/index'
+import { locale } from '../locales/index'
+import { loadRole } from '../service/machines'
+
+export const sectionFeature = defineRegister<ClientContext>((controller, ctx) => {
+ void loadRole().then((role) => {
+ if (controller.isDisposed() || role?.remote !== false)
+ return
+ controller.add(ctx.slots.inject(SETTINGS_SECTION_SLOT as never, () => ctx.slots.register({
+ name: SETTINGS_SECTION_SLOT,
+ id: SETTINGS_SECTION_ID,
+ order: SETTINGS_SECTION_ORDER,
+ label: () => locale.text('nav'),
+ locale: locale.NS,
+ } as never, RemoteSection as never)))
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/client/service/access.test.ts b/packages/dsh-tauri-remote/src/client/service/access.test.ts
new file mode 100644
index 00000000..78e87145
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/service/access.test.ts
@@ -0,0 +1,107 @@
+import type { WireCall, WireReply } from '../test-utils/client-mock'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { store } from '../store/index'
+import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
+import * as service from './access'
+
+vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
+
+const BASE = '/api/tauri/remote/access'
+
+let queued: WireReply[] = []
+let route: (call: WireCall) => WireReply = () => replies.ok({})
+
+function once(...next: WireReply[]): void {
+ queued.push(...next)
+}
+
+beforeEach(() => {
+ resetWire()
+ store.access.reset()
+ queued = []
+ route = () => replies.ok({})
+ answer(call => queued.shift() ?? route(call))
+})
+
+describe('接入面板数据层', () => {
+ it('回包缺字段时按默认值收敛,绝不抛错', async () => {
+ route = () => replies.ok({ state: 'listening', listening: true })
+ await service.load()
+ const snapshot = store.access.snapshot
+ expect(store.access.status).toBe('ready')
+ expect(snapshot?.state).toBe('listening')
+ expect(snapshot?.listen).toEqual({ address: '127.0.0.1', port: 3088 })
+ expect(snapshot?.tunnel).toEqual({ enabled: false, mode: 'quick', hostname: null, state: 'stopped', events: [] })
+ expect(snapshot?.addresses).toEqual([])
+ })
+
+ it('字段类型不对时逐项回落,保留可用部分', async () => {
+ route = () => replies.ok({
+ version: 'v1',
+ enabled: true,
+ port: '3088',
+ auth: { enabled: true, scope: 'everything', hasToken: 'yes' },
+ addresses: [{ address: '10.0.0.2' }, { nope: true }, 'garbage'],
+ tunnel: { enabled: true, mode: 'named', state: 'running', hostname: 'dsh.example.com' },
+ events: [{ seq: 2, line: 'ok' }, { nope: 1 }],
+ })
+ await service.load()
+ const snapshot = store.access.snapshot
+ expect(snapshot?.version).toBe(1)
+ expect(snapshot?.port).toBe(0)
+ expect(snapshot?.auth).toEqual({ enabled: true, scope: 'public_only' })
+ expect(snapshot?.addresses).toHaveLength(1)
+ expect(snapshot?.addresses[0]?.address).toBe('10.0.0.2')
+ expect(snapshot?.tunnel.mode).toBe('quick')
+ expect(snapshot?.tunnel.state).toBe('running')
+ expect(snapshot?.events).toEqual([{ seq: 2, ts: '', kind: 'state', line: 'ok' }])
+ })
+
+ it('配对回包保留合法消费序号,非法序号不覆盖可用凭据', async () => {
+ const pairing = { code: 'AB23CD45', expiresAt: 300000 }
+ const cases: { value: unknown, expected?: number }[] = [
+ { value: 0, expected: 0 },
+ { value: 2, expected: 2 },
+ { value: Number.MAX_SAFE_INTEGER, expected: Number.MAX_SAFE_INTEGER },
+ { value: -1 },
+ { value: 0.5 },
+ { value: '2' },
+ { value: undefined },
+ { value: Number.NaN },
+ { value: Number.POSITIVE_INFINITY },
+ { value: Number.MAX_SAFE_INTEGER + 1 },
+ ]
+ for (const { value, expected } of cases) {
+ route = () => replies.ok({ auth: { token: '01234567' }, pairing: { ...pairing, usedSeq: value } })
+ await service.refresh()
+ expect(store.access.snapshot?.auth.token).toBe('01234567')
+ expect(store.access.snapshot?.pairing).toEqual(expected === undefined ? pairing : { ...pairing, usedSeq: expected })
+ }
+ })
+
+ it('变更失败时保留错误文案并复位 busy', async () => {
+ once(replies.ok({}), replies.fail('访问密码太短', 400))
+ await service.load()
+ const result = await service.apply({ password: 'x' })
+ expect(result.ok).toBe(false)
+ expect(result.error).toContain('访问密码太短')
+ expect(store.access.status).toBe('error')
+ expect(store.access.busy).toBe(false)
+ })
+
+ it('隧道启停走面板专用路由并提交回包', async () => {
+ once(
+ replies.ok({}),
+ replies.ok({ enabled: true, tunnel: { enabled: true, mode: 'token', hostname: 'dsh.example.com', state: 'running', events: [] } }),
+ replies.ok({ enabled: true, tunnel: { enabled: false, mode: 'token', hostname: 'dsh.example.com', state: 'stopped', events: [] } }),
+ )
+ await service.load()
+ await service.startTunnel({ mode: 'token', token: 'cf', hostname: 'dsh.example.com' })
+ expect(sent.at(-1)?.url).toBe(`${BASE}/tunnel`)
+ expect(sent.at(-1)?.http).toBe('POST')
+ expect(store.access.snapshot?.tunnel.state).toBe('running')
+ await service.stopTunnel()
+ expect(sent.at(-1)?.http).toBe('DELETE')
+ expect(store.access.snapshot?.tunnel.state).toBe('stopped')
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/client/service/access.ts b/packages/dsh-tauri-remote/src/client/service/access.ts
new file mode 100644
index 00000000..20712281
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/service/access.ts
@@ -0,0 +1,254 @@
+import type { AccessAddress, AccessBody, AccessEvent, AccessLinkSource, AccessPairing, AccessScope, AccessState, AccessStatus, AccessTunnel, ServiceResult, TunnelBody, TunnelMode, TunnelProgress, TunnelProgressStage, TunnelState } from '../types/index'
+import { ofetch as request } from 'dsh-tauri/client'
+import { messageOf } from '../../shared/error'
+import { store } from '../store/index'
+
+const BASE = '/api/tauri/remote/access'
+
+const SCOPES: readonly AccessScope[] = ['public_only', 'all']
+const LINK_SOURCES: readonly AccessLinkSource[] = ['loopback', 'lan']
+const ACCESS_STATES: readonly AccessState[] = ['stopped', 'listening', 'error']
+const TUNNEL_MODES: readonly TunnelMode[] = ['quick', 'token']
+const TUNNEL_STATES: readonly TunnelState[] = ['stopped', 'starting', 'running', 'error']
+const TUNNEL_PROGRESS_STAGES: readonly TunnelProgressStage[] = ['check', 'download', 'extract', 'verify', 'spawn', 'domain', 'ready']
+
+const EMPTY_TUNNEL: AccessTunnel = { enabled: false, mode: 'quick', hostname: null, state: 'stopped', events: [] }
+
+let requests = 0
+let lastSaved = 0
+
+export async function load(): Promise<void> {
+ store.access.beginLoad()
+ await refresh()
+}
+
+/** 轮询用:不改状态机的 loading 档,避免面板在后台刷新时闪回加载态。 */
+export async function refresh(): Promise<void> {
+ const mine = ++requests
+ try {
+ const next = accessStatusOf(await request<unknown>(BASE, { method: 'get' }))
+ if (mine >= lastSaved)
+ store.access.commit(next)
+ }
+ catch (error) {
+ if (mine >= lastSaved)
+ store.access.fail(messageOf(error))
+ }
+}
+
+export async function apply(body: AccessBody): Promise<ServiceResult> {
+ return await mutate(async () => await request<unknown>(BASE, { method: 'post', body }))
+}
+
+export async function rotateToken(): Promise<ServiceResult> {
+ return await mutate(async () => await request<unknown>(`${BASE}/token`, { method: 'post' }))
+}
+
+export async function revokeToken(): Promise<ServiceResult> {
+ return await mutate(async () => await request<unknown>(`${BASE}/token`, { method: 'delete' }))
+}
+
+export async function startTunnel(body: TunnelBody): Promise<ServiceResult> {
+ return await mutate(async () => await request<unknown>(`${BASE}/tunnel`, { method: 'post', body }))
+}
+
+export async function stopTunnel(): Promise<ServiceResult> {
+ return await mutate(async () => await request<unknown>(`${BASE}/tunnel`, { method: 'delete' }))
+}
+
+// --- internal ---
+async function mutate(run: () => Promise<unknown>): Promise<ServiceResult> {
+ const mine = ++requests
+ store.access.beginBusy()
+ try {
+ const next = accessStatusOf(await run())
+ lastSaved = Math.max(lastSaved, mine)
+ store.access.commit(next)
+ return { ok: true }
+ }
+ catch (error) {
+ const message = messageOf(error)
+ store.access.fail(message)
+ return { ok: false, error: message }
+ }
+ finally {
+ store.access.endBusy()
+ }
+}
+
+function accessStatusOf(value: unknown): AccessStatus {
+ const raw = recordOf(value)
+ const listening = booleanOf(raw.listening) ?? false
+ const tunnel = tunnelOf(raw.tunnel)
+ return {
+ version: numberOf(raw.version) ?? 1,
+ enabled: booleanOf(raw.enabled) ?? false,
+ state: stateOf(raw.state) ?? (listening ? 'listening' : 'stopped'),
+ listening,
+ listen: listenOf(raw.listen),
+ port: numberOf(raw.port) ?? 0,
+ auth: authOf(raw.auth),
+ addresses: listOf(raw.addresses).map(addressOf).filter(entry => entry !== undefined),
+ tunnel,
+ events: listOf(raw.events).map(eventOf).filter(entry => entry !== undefined),
+ ...textField('recommended', raw.recommended),
+ ...linkSourceField(raw.linkSource),
+ ...textField('generatedPassword', raw.generatedPassword),
+ ...textField('link', raw.link),
+ ...textField('maskLink', raw.maskLink),
+ ...textField('qr', raw.qr),
+ ...textField('error', raw.error),
+ ...numberField('localPort', raw.localPort),
+ ...warningsField(raw.warnings),
+ ...pairingField(raw.pairing),
+ }
+}
+
+function pairingField(value: unknown): { pairing?: AccessPairing } {
+ const raw = recordOf(value)
+ const code = textOf(raw.code)
+ const expiresAt = numberOf(raw.expiresAt)
+ if (code === undefined || expiresAt === undefined)
+ return {}
+ const link = textOf(raw.link)
+ const qr = textOf(raw.qr)
+ const tunnelLink = textOf(raw.tunnelLink)
+ const tunnelQr = textOf(raw.tunnelQr)
+ const usedSeq = numberOf(raw.usedSeq)
+ return { pairing: { code, expiresAt, ...usedSeq !== undefined && Number.isSafeInteger(usedSeq) && usedSeq >= 0 ? { usedSeq } : {}, ...link === undefined ? {} : { link }, ...qr === undefined ? {} : { qr }, ...tunnelLink === undefined ? {} : { tunnelLink }, ...tunnelQr === undefined ? {} : { tunnelQr } } }
+}
+
+function listenOf(value: unknown): { address: string, port: number } {
+ const raw = recordOf(value)
+ return { address: textOf(raw.address) ?? '127.0.0.1', port: numberOf(raw.port) ?? 3088 }
+}
+
+function authOf(value: unknown): AccessStatus['auth'] {
+ const raw = recordOf(value)
+ return {
+ enabled: booleanOf(raw.enabled) ?? false,
+ scope: scopeOf(raw.scope) ?? 'public_only',
+ ...booleanField('hasPassword', raw.hasPassword),
+ ...booleanField('hasToken', raw.hasToken),
+ ...textField('token', raw.token),
+ }
+}
+
+function addressOf(value: unknown): AccessAddress | undefined {
+ const raw = recordOf(value)
+ const address = textOf(raw.address)
+ if (address === undefined)
+ return undefined
+ return {
+ address,
+ family: textOf(raw.family) ?? (address.includes(':') ? 'ipv6' : 'ipv4'),
+ interface: textOf(raw.interface) ?? '',
+ scope: textOf(raw.scope) ?? 'private',
+ score: numberOf(raw.score) ?? 0,
+ recommended: booleanOf(raw.recommended) ?? false,
+ }
+}
+
+function tunnelOf(value: unknown): AccessTunnel {
+ const raw = recordOf(value)
+ if (Object.keys(raw).length === 0)
+ return { ...EMPTY_TUNNEL }
+ return {
+ enabled: booleanOf(raw.enabled) ?? false,
+ mode: modeOf(raw.mode) ?? 'quick',
+ hostname: textOf(raw.hostname) ?? null,
+ state: tunnelStateOf(raw.state) ?? 'stopped',
+ events: listOf(raw.events).map(eventOf).filter(entry => entry !== undefined),
+ ...textField('token', raw.token),
+ ...textField('url', raw.url),
+ ...textField('link', raw.link),
+ ...progressField(raw.progress),
+ ...textField('qr', raw.qr),
+ ...textField('error', raw.error),
+ ...numberField('port', raw.port),
+ }
+}
+
+function eventOf(value: unknown): AccessEvent | undefined {
+ const raw = recordOf(value)
+ const line = textOf(raw.line)
+ if (line === undefined)
+ return undefined
+ return { seq: numberOf(raw.seq) ?? 0, ts: textOf(raw.ts) ?? '', kind: textOf(raw.kind) ?? 'state', line }
+}
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return typeof value === 'object' && value !== null ? value as Record<string, unknown> : {}
+}
+
+function listOf(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : []
+}
+
+function textOf(value: unknown): string | undefined {
+ return typeof value === 'string' && value !== '' ? value : undefined
+}
+
+function numberOf(value: unknown): number | undefined {
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined
+}
+
+function booleanOf(value: unknown): boolean | undefined {
+ return typeof value === 'boolean' ? value : undefined
+}
+
+function stateOf(value: unknown): AccessState | undefined {
+ return ACCESS_STATES.find(candidate => candidate === value)
+}
+
+function scopeOf(value: unknown): AccessScope | undefined {
+ return SCOPES.find(candidate => candidate === value)
+}
+
+function modeOf(value: unknown): TunnelMode | undefined {
+ return TUNNEL_MODES.find(candidate => candidate === value)
+}
+
+function tunnelStateOf(value: unknown): TunnelState | undefined {
+ return TUNNEL_STATES.find(candidate => candidate === value)
+}
+
+function progressField(value: unknown): { progress: TunnelProgress } | Record<string, never> {
+ const raw = recordOf(value)
+ const stage = TUNNEL_PROGRESS_STAGES.find(candidate => candidate === raw.stage)
+ if (stage === undefined)
+ return {}
+ return {
+ progress: {
+ stage,
+ ...textField('url', raw.url),
+ ...numberField('received', raw.received),
+ ...numberField('total', raw.total),
+ },
+ }
+}
+
+function linkSourceField(value: unknown): { linkSource: AccessLinkSource } | Record<string, never> {
+ const source = LINK_SOURCES.find(candidate => candidate === value)
+ return source === undefined ? {} : { linkSource: source }
+}
+
+function textField<K extends string>(key: K, value: unknown): Record<K, string> | Record<string, never> {
+ const text = textOf(value)
+ return text === undefined ? {} : { [key]: text } as Record<K, string>
+}
+
+function numberField<K extends string>(key: K, value: unknown): Record<K, number> | Record<string, never> {
+ const number = numberOf(value)
+ return number === undefined ? {} : { [key]: number } as Record<K, number>
+}
+
+function booleanField<K extends string>(key: K, value: unknown): Record<K, boolean> | Record<string, never> {
+ const boolean = booleanOf(value)
+ return boolean === undefined ? {} : { [key]: boolean } as Record<K, boolean>
+}
+
+function warningsField(value: unknown): { warnings: string[] } | Record<string, never> {
+ const warnings = listOf(value).map(textOf).filter(entry => entry !== undefined)
+ return warnings.length === 0 ? {} : { warnings }
+}
diff --git a/packages/dsh-tauri-ssh/src/client/service/bridge.ts b/packages/dsh-tauri-remote/src/client/service/bridge.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/client/service/bridge.ts
rename to packages/dsh-tauri-remote/src/client/service/bridge.ts
diff --git a/packages/dsh-tauri-ssh/src/client/service/machines.test.ts b/packages/dsh-tauri-remote/src/client/service/machines.test.ts
similarity index 91%
rename from packages/dsh-tauri-ssh/src/client/service/machines.test.ts
rename to packages/dsh-tauri-remote/src/client/service/machines.test.ts
index 67344bdf..c3c4ba3c 100644
--- a/packages/dsh-tauri-ssh/src/client/service/machines.test.ts
+++ b/packages/dsh-tauri-remote/src/client/service/machines.test.ts
@@ -6,9 +6,11 @@ import { store } from '../store/index'
import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
import * as service from './machines'
+const baseURL = '/api/tauri/remote'
+
vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
-const API = '/api/tauri/ssh'
+const API = baseURL
const machineA: MachineRow = {
id: 'a',
@@ -42,7 +44,7 @@ function wireList(items: readonly unknown[], discovered: readonly unknown[] = []
answer((call) => {
if (call.url === `${API}/machines`)
return replies.ok({ items, discovered })
- return replies.ok(call.url === `${API}/session/role` ? { remote: false } : {})
+ return replies.ok(call.url === `${API}/session/role` ? { role: 'local', remote: false } : {})
})
}
@@ -52,6 +54,39 @@ beforeEach(() => {
store.sync.reset()
})
+describe('loadRole', () => {
+ it.each([
+ { role: 'local', remote: false },
+ { role: 'remote', remote: true, origin: 'ops' },
+ ])('returns and stores the freshly confirmed role: %j', async (value) => {
+ store.machines.setRole({ remote: !value.remote })
+ answer(() => replies.ok(value))
+ const expected = value.remote ? { remote: true, origin: 'ops' } : { remote: false }
+ await expect(service.loadRole()).resolves.toEqual(expected)
+ expect(store.machines.role).toEqual(expected)
+ expect(callsOf('/session/role', 'GET')).toHaveLength(1)
+ })
+
+ it.each([
+ {},
+ { remote: false },
+ { role: 'remote', remote: false },
+ { role: 'local', remote: false, error: 'denied' },
+ ])('returns unknown instead of a cached local role for malformed responses: %j', async (value) => {
+ store.machines.setRole({ remote: false })
+ answer(() => replies.ok(value))
+ await expect(service.loadRole()).resolves.toBeNull()
+ expect(callsOf('/session/role', 'GET')).toHaveLength(1)
+ })
+
+ it('returns unknown instead of a cached local role when the role probe fails', async () => {
+ store.machines.setRole({ remote: false })
+ answer(() => replies.fail('denied', 403))
+ await expect(service.loadRole()).resolves.toBeNull()
+ expect(callsOf('/session/role', 'GET')).toHaveLength(1)
+ })
+})
+
describe('load', () => {
it('loads the machines, their secret flags, and their live statuses', async () => {
wireList([
@@ -147,7 +182,7 @@ describe('load', () => {
describe('persist', () => {
it('saves the edited rows, the typed secrets, and removes the vanished machines', async () => {
let items: readonly unknown[] = [machineA, machineB]
- answer(call => call.url === `${API}/machines` ? replies.ok({ items, discovered: [] }) : replies.ok({ remote: false }))
+ answer(call => call.url === `${API}/machines` ? replies.ok({ items, discovered: [] }) : replies.ok({ role: 'local', remote: false }))
await service.load()
const renamed = { ...machineA, name: 'alpha-2' }
items = [renamed]
@@ -266,11 +301,11 @@ describe('machine actions', () => {
answer(() => replies.empty())
await service.connect({ machineId: 'a' })
- expect(store.machines.error).toBe('SSH_API_EMPTY')
+ expect(store.machines.error).toBe('REMOTE_API_EMPTY')
answer(() => replies.http(405))
await service.connect({ machineId: 'a' })
- expect(store.machines.error).toBe('SSH_API_HTTP_405')
+ expect(store.machines.error).toBe('REMOTE_API_HTTP_405')
})
it('records an install result and reloads the list', async () => {
@@ -310,7 +345,7 @@ describe('feature switch', () => {
return replies.ok({ enabled: call.http === 'POST' })
if (call.url === `${API}/machines`)
return replies.ok({ items: [machineA], discovered: [] })
- return replies.ok({ remote: false })
+ return replies.ok({ role: 'local', remote: false })
})
await service.loadSettings()
await expect(service.setEnabled(true)).resolves.toEqual({ ok: true })
@@ -341,7 +376,7 @@ describe('feature switch', () => {
answer(() => replies.http(405))
await service.loadSettings()
expect(store.machines.enabled).toBe(false)
- expect(store.machines.error).toBe('SSH_API_HTTP_405')
+ expect(store.machines.error).toBe('REMOTE_API_HTTP_405')
})
})
diff --git a/packages/dsh-tauri-ssh/src/client/service/machines.ts b/packages/dsh-tauri-remote/src/client/service/machines.ts
similarity index 89%
rename from packages/dsh-tauri-ssh/src/client/service/machines.ts
rename to packages/dsh-tauri-remote/src/client/service/machines.ts
index 08592843..2808e12c 100644
--- a/packages/dsh-tauri-ssh/src/client/service/machines.ts
+++ b/packages/dsh-tauri-remote/src/client/service/machines.ts
@@ -1,5 +1,5 @@
import type { MachineBusyOp } from '../store/modules/machines.types'
-import type { SecretValues, ServiceResult, SshMachineEvent } from '../types/index'
+import type { RemoteMachineEvent, SecretValues, ServiceResult } from '../types/index'
import type { PersistMachinesInput } from './machines.types'
import { uniq } from 'dsh-tauri/client'
import * as api from '../apis/index'
@@ -9,9 +9,10 @@ import {
installResultOf,
machineEventsOf,
machineListOf,
+ REMOTE_API_EMPTY,
savePayloadOf,
sessionRoleOf,
- SSH_API_EMPTY,
+ settingsWarningOf,
testResultOf,
tunnelUrlOf,
} from '../apis/parsers'
@@ -21,18 +22,25 @@ const NO_SECRETS: SecretValues = {}
export async function loadSettings(): Promise<void> {
try {
- store.machines.setEnabled(enabledOf(await api.getSettings()) === true, null)
+ const settings = await api.getSettings()
+ store.machines.setMigrationWarning(settingsWarningOf(settings))
+ store.machines.setEnabled(enabledOf(settings) === true, null)
}
catch (error) {
store.machines.setEnabled(false, errorMessageOf(error))
}
}
-export async function loadRole(): Promise<void> {
+export async function loadRole(): Promise<ReturnType<typeof sessionRoleOf>> {
try {
- store.machines.setRole(sessionRoleOf(await api.getSessionRole()))
+ const role = sessionRoleOf(await api.getSessionRole())
+ if (role !== null)
+ store.machines.setRole(role)
+ return role
+ }
+ catch {
+ return null
}
- catch {}
}
export async function load(): Promise<void> {
@@ -125,7 +133,7 @@ export async function connect(input: { machineId: string }): Promise<ServiceResu
return withBusy(input.machineId, 'connect', async () => {
const tunnelBaseUrl = tunnelUrlOf(await api.postMachinesConnect({ machineId: input.machineId }))
if (tunnelBaseUrl === '')
- throw new Error(SSH_API_EMPTY)
+ throw new Error(REMOTE_API_EMPTY)
store.machines.commitConnected(input.machineId, tunnelBaseUrl)
})
}
@@ -190,7 +198,7 @@ async function pollEvents(): Promise<void> {
store.machines.appendLogs(lines)
}
-function logLineOf(event: SshMachineEvent): string {
+function logLineOf(event: RemoteMachineEvent): string {
if (event.line !== '')
return event.line
if (event.terminal === 'failed')
diff --git a/packages/dsh-tauri-ssh/src/client/service/machines.types.ts b/packages/dsh-tauri-remote/src/client/service/machines.types.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/client/service/machines.types.ts
rename to packages/dsh-tauri-remote/src/client/service/machines.types.ts
diff --git a/packages/dsh-tauri-ssh/src/client/service/sync.test.ts b/packages/dsh-tauri-remote/src/client/service/sync.test.ts
similarity index 99%
rename from packages/dsh-tauri-ssh/src/client/service/sync.test.ts
rename to packages/dsh-tauri-remote/src/client/service/sync.test.ts
index f87af903..a2a515b0 100644
--- a/packages/dsh-tauri-ssh/src/client/service/sync.test.ts
+++ b/packages/dsh-tauri-remote/src/client/service/sync.test.ts
@@ -4,7 +4,7 @@ import { store } from '../store/index'
import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
import * as service from './sync'
-const baseURL = '/api/tauri/ssh'
+const baseURL = '/api/tauri/remote'
vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
diff --git a/packages/dsh-tauri-ssh/src/client/service/sync.ts b/packages/dsh-tauri-remote/src/client/service/sync.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/client/service/sync.ts
rename to packages/dsh-tauri-remote/src/client/service/sync.ts
diff --git a/packages/dsh-tauri-ssh/src/client/service/sync.types.ts b/packages/dsh-tauri-remote/src/client/service/sync.types.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/client/service/sync.types.ts
rename to packages/dsh-tauri-remote/src/client/service/sync.types.ts
diff --git a/packages/dsh-tauri-remote/src/client/store/index.ts b/packages/dsh-tauri-remote/src/client/store/index.ts
new file mode 100644
index 00000000..00ab6f43
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/store/index.ts
@@ -0,0 +1,5 @@
+import { access } from './modules/access'
+import { machines } from './modules/machines'
+import { sync } from './modules/sync'
+
+export const store = { machines, sync, access }
diff --git a/packages/dsh-tauri-remote/src/client/store/modules/access.ts b/packages/dsh-tauri-remote/src/client/store/modules/access.ts
new file mode 100644
index 00000000..42547c4f
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/store/modules/access.ts
@@ -0,0 +1,40 @@
+import type { AccessStatus } from '../../types/index'
+import type { AccessViewState } from './access.types'
+import { defineStore } from 'dsh-tauri/client'
+
+function initialState(): AccessViewState {
+ return {
+ status: 'idle',
+ error: null,
+ busy: false,
+ snapshot: null,
+ }
+}
+
+export const access = defineStore({
+ state: (): AccessViewState => initialState(),
+ actions: {
+ reset(): void {
+ Object.assign(this, initialState())
+ },
+ beginLoad(): void {
+ this.status = 'loading'
+ this.error = null
+ },
+ commit(snapshot: AccessStatus): void {
+ this.snapshot = snapshot
+ this.status = 'ready'
+ this.error = null
+ },
+ fail(message: string): void {
+ this.status = 'error'
+ this.error = message
+ },
+ beginBusy(): void {
+ this.busy = true
+ },
+ endBusy(): void {
+ this.busy = false
+ },
+ },
+})
diff --git a/packages/dsh-tauri-remote/src/client/store/modules/access.types.ts b/packages/dsh-tauri-remote/src/client/store/modules/access.types.ts
new file mode 100644
index 00000000..404f3cc5
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/store/modules/access.types.ts
@@ -0,0 +1,10 @@
+import type { AccessStatus } from '../../types/index'
+
+export type AccessLoadStatus = 'idle' | 'loading' | 'ready' | 'error'
+
+export interface AccessViewState {
+ status: AccessLoadStatus
+ error: string | null
+ busy: boolean
+ snapshot: AccessStatus | null
+}
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/machines.test.ts b/packages/dsh-tauri-remote/src/client/store/modules/machines.test.ts
similarity index 93%
rename from packages/dsh-tauri-ssh/src/client/store/modules/machines.test.ts
rename to packages/dsh-tauri-remote/src/client/store/modules/machines.test.ts
index 6f1dc382..fe74a509 100644
--- a/packages/dsh-tauri-ssh/src/client/store/modules/machines.test.ts
+++ b/packages/dsh-tauri-remote/src/client/store/modules/machines.test.ts
@@ -124,6 +124,15 @@ describe('the feature switch', () => {
})
})
+describe('the migration warning', () => {
+ it('carries the host warning until a later read reports none', () => {
+ store.machines.setMigrationWarning('ssh/machines.json 不是合法 JSON')
+ expect(store.machines.migrationWarning).toBe('ssh/machines.json 不是合法 JSON')
+ store.machines.setMigrationWarning(null)
+ expect(store.machines.migrationWarning).toBeNull()
+ })
+})
+
describe('event cursors', () => {
it('only ever moves a cursor forward', () => {
store.machines.advanceEvents({ a: 5 })
@@ -159,6 +168,7 @@ describe('reset', () => {
notice: null,
installResults: {},
role: null,
+ migrationWarning: null,
eventCursors: {},
eventsSupported: true,
})
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/machines.ts b/packages/dsh-tauri-remote/src/client/store/modules/machines.ts
similarity index 97%
rename from packages/dsh-tauri-ssh/src/client/store/modules/machines.ts
rename to packages/dsh-tauri-remote/src/client/store/modules/machines.ts
index 85a8e9ed..c0475312 100644
--- a/packages/dsh-tauri-ssh/src/client/store/modules/machines.ts
+++ b/packages/dsh-tauri-remote/src/client/store/modules/machines.ts
@@ -19,6 +19,7 @@ function initialState(): MachinesState {
notice: null,
installResults: {},
role: null,
+ migrationWarning: null,
eventCursors: {},
eventsSupported: true,
}
@@ -80,6 +81,9 @@ export const machines = defineStore({
setRole(role: { remote: boolean, origin?: string }): void {
this.role = role
},
+ setMigrationWarning(warning: string | null): void {
+ this.migrationWarning = warning
+ },
beginOp(id: string, op: MachineBusyOp): void {
this.busy[id] = op
this.notice = null
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/machines.types.ts b/packages/dsh-tauri-remote/src/client/store/modules/machines.types.ts
similarity index 83%
rename from packages/dsh-tauri-ssh/src/client/store/modules/machines.types.ts
rename to packages/dsh-tauri-remote/src/client/store/modules/machines.types.ts
index 8a38d215..f711db46 100644
--- a/packages/dsh-tauri-ssh/src/client/store/modules/machines.types.ts
+++ b/packages/dsh-tauri-remote/src/client/store/modules/machines.types.ts
@@ -1,4 +1,4 @@
-import type { SshKey } from '../../locales/index'
+import type { RemoteKey } from '../../locales/index'
import type {
InstallResult,
MachineRow,
@@ -12,7 +12,7 @@ export type MachineBusyOp = 'test' | 'connect' | 'disconnect' | 'install'
export type MachinesNotice
= | { kind: 'text', text: string }
- | { kind: 'key', key: SshKey, params?: Record<string, string | number> }
+ | { kind: 'key', key: RemoteKey, params?: Record<string, string | number> }
export interface MachinesState {
status: MachinesStatus
@@ -28,6 +28,7 @@ export interface MachinesState {
notice: MachinesNotice | null
installResults: Record<string, InstallResult>
role: { remote: boolean, origin?: string } | null
+ migrationWarning: string | null
eventCursors: Record<string, number>
eventsSupported: boolean
}
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/sync.ts b/packages/dsh-tauri-remote/src/client/store/modules/sync.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/client/store/modules/sync.ts
rename to packages/dsh-tauri-remote/src/client/store/modules/sync.ts
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/sync.types.ts b/packages/dsh-tauri-remote/src/client/store/modules/sync.types.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/client/store/modules/sync.types.ts
rename to packages/dsh-tauri-remote/src/client/store/modules/sync.types.ts
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/sync.utils.test.ts b/packages/dsh-tauri-remote/src/client/store/modules/sync.utils.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/client/store/modules/sync.utils.test.ts
rename to packages/dsh-tauri-remote/src/client/store/modules/sync.utils.test.ts
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/sync.utils.ts b/packages/dsh-tauri-remote/src/client/store/modules/sync.utils.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/client/store/modules/sync.utils.ts
rename to packages/dsh-tauri-remote/src/client/store/modules/sync.utils.ts
diff --git a/packages/dsh-tauri-ssh/src/client/test-utils/client-mock.ts b/packages/dsh-tauri-remote/src/client/test-utils/client-mock.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/client/test-utils/client-mock.ts
rename to packages/dsh-tauri-remote/src/client/test-utils/client-mock.ts
diff --git a/packages/dsh-tauri-ssh/src/client/test-utils/ui-mock.ts b/packages/dsh-tauri-remote/src/client/test-utils/ui-mock.ts
similarity index 76%
rename from packages/dsh-tauri-ssh/src/client/test-utils/ui-mock.ts
rename to packages/dsh-tauri-remote/src/client/test-utils/ui-mock.ts
index 1349e1cb..62277382 100644
--- a/packages/dsh-tauri-ssh/src/client/test-utils/ui-mock.ts
+++ b/packages/dsh-tauri-remote/src/client/test-utils/ui-mock.ts
@@ -32,6 +32,28 @@ function StateDot(): ReactNode {
return null
}
+function Field({ label, children, ...rest }: Props): ReactNode {
+ return createElement('div', rest, createElement('span', null, label as never), children as never)
+}
+
+function Select({ options, value, onChange, label, ...rest }: Props & {
+ options: Array<{ value: string, label: string }>
+ value: string
+ onChange: (next: string) => void
+ label?: string
+}): ReactNode {
+ return createElement(
+ 'select',
+ {
+ 'aria-label': label,
+ 'value': value,
+ 'onChange': (event: { target: { value: string } }) => onChange(event.target.value),
+ ...rest,
+ },
+ options.map(option => createElement('option', { key: option.value, value: option.value }, option.label)),
+ )
+}
+
function Globe(): ReactNode {
return null
}
@@ -84,12 +106,14 @@ function Switch({ checked, onChange, label, disabled, title, className }: {
export const uiMock = {
Button,
+ Field,
Globe,
Icon,
Input,
Modal,
Pill,
SegmentedControl,
+ Select,
StateDot,
Switch,
}
diff --git a/packages/dsh-tauri-remote/src/client/types/index.ts b/packages/dsh-tauri-remote/src/client/types/index.ts
new file mode 100644
index 00000000..73f3289e
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/types/index.ts
@@ -0,0 +1,210 @@
+export type MachineLifecycleState
+ = | 'disconnected'
+ | 'testing'
+ | 'connecting'
+ | 'connected'
+ | 'reconnecting'
+ | 'given-up'
+
+export interface ServiceResult {
+ ok: boolean
+ error?: string
+}
+
+export function isLifecycleState(value: unknown): value is MachineLifecycleState {
+ return value === 'disconnected'
+ || value === 'testing'
+ || value === 'connecting'
+ || value === 'connected'
+ || value === 'reconnecting'
+ || value === 'given-up'
+}
+
+export interface MachineRow {
+ id: string
+ name: string
+ host: string
+ port: number
+ user: string
+ hasPassword: boolean
+ hasPassphrase: boolean
+ remotePort: number
+ profileName?: string
+ startCommand?: string
+ color?: string
+ tintBorder?: boolean
+}
+
+export interface SecretValues {
+ password?: string
+ passphrase?: string
+}
+
+export type ProgressPhase = 'handshake' | 'installing' | 'starting' | 'probing' | 'syncing'
+
+export interface MachineStatus {
+ state: MachineLifecycleState
+ nextRetryAt?: number
+ authMethod?: 'agent' | 'key' | 'password'
+ tunnelBaseUrl?: string
+ lastError?: string
+ dshMissing?: boolean
+ progress?: { phase: ProgressPhase, attempt?: number, total?: number, item?: string, log?: string }
+}
+
+export interface MachineListSnapshot {
+ machines: MachineRow[]
+ discovered: MachineRow[]
+ statuses: Record<string, MachineStatus>
+}
+
+export interface InstallResult {
+ dshPath: string
+ credentialsCopied: boolean
+ credentialsError?: string
+}
+
+export interface RemoteMachineEvent {
+ seq: number
+ ts: string
+ machineId: string
+ stage: string
+ line: string
+ terminal?: 'success' | 'failed'
+ reason?: string
+}
+
+export interface SyncPluginItem {
+ name: string
+ spec: string
+ syncable: boolean
+ reason?: string
+}
+
+export interface SyncSkillItem {
+ name: string
+ root: string
+}
+
+export interface SyncPreview {
+ plugins: SyncPluginItem[]
+ skills: SyncSkillItem[]
+}
+
+export interface SyncItemResult {
+ kind: 'plugin' | 'skill'
+ name: string
+ root?: string
+ ok: boolean
+ error?: string
+ log?: string
+}
+
+export interface SyncApplyResult {
+ items: SyncItemResult[]
+}
+
+export interface RemoteBridge {
+ probe: () => Promise<unknown>
+ openWindow: (machineId: string, url: string) => Promise<unknown>
+}
+
+export type AccessState = 'stopped' | 'listening' | 'error'
+
+export type AccessScope = 'public_only' | 'all'
+
+export type TunnelMode = 'quick' | 'token'
+
+export type TunnelState = 'stopped' | 'starting' | 'running' | 'error'
+
+export interface AccessAddress {
+ address: string
+ family: string
+ interface: string
+ scope: string
+ score: number
+ recommended: boolean
+}
+
+export interface AccessEvent {
+ seq: number
+ ts: string
+ kind: string
+ line: string
+}
+
+export interface AccessTunnel {
+ enabled: boolean
+ mode: TunnelMode
+ hostname: string | null
+ state: TunnelState
+ events: readonly AccessEvent[]
+ token?: string
+ url?: string
+ port?: number
+ link?: string
+ qr?: string
+ progress?: TunnelProgress
+ error?: string
+}
+
+export type AccessLinkSource = 'loopback' | 'lan'
+
+export type TunnelProgressStage = 'check' | 'download' | 'extract' | 'verify' | 'spawn' | 'domain' | 'ready'
+
+export interface TunnelProgress {
+ stage: TunnelProgressStage
+ url?: string
+ received?: number
+ total?: number
+}
+
+/** 临时配对码:宿主生成、5 分钟轮换;分享链接与二维码只携带它。 */
+export interface AccessPairing {
+ code: string
+ expiresAt: number
+ usedSeq?: number
+ link?: string
+ qr?: string
+ tunnelLink?: string
+ tunnelQr?: string
+}
+
+export interface AccessStatus {
+ version: number
+ enabled: boolean
+ state: AccessState
+ listening: boolean
+ listen: { address: string, port: number }
+ port: number
+ auth: { enabled: boolean, scope: AccessScope, hasPassword?: boolean, hasToken?: boolean, token?: string }
+ addresses: readonly AccessAddress[]
+ recommended?: string
+ link?: string
+ maskLink?: string
+ qr?: string
+ linkSource?: AccessLinkSource
+ pairing?: AccessPairing
+ generatedPassword?: string
+ tunnel: AccessTunnel
+ localPort?: number
+ error?: string
+ warnings?: readonly string[]
+ events: readonly AccessEvent[]
+}
+
+export interface AccessBody {
+ enabled?: boolean
+ address?: string
+ port?: number
+ authEnabled?: boolean
+ scope?: AccessScope
+ /** `null` 表示清除已设密码。 */
+ password?: string | null
+}
+
+export interface TunnelBody {
+ mode: TunnelMode
+ token?: string
+ hostname?: string
+}
diff --git a/packages/dsh-tauri-remote/src/client/utils/access-form.test.ts b/packages/dsh-tauri-remote/src/client/utils/access-form.test.ts
new file mode 100644
index 00000000..07eeae3e
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/utils/access-form.test.ts
@@ -0,0 +1,63 @@
+import type { AccessTunnel } from '../types/index'
+import { describe, expect, it } from 'vitest'
+import {
+ countdownOf,
+ lanDirtyOf,
+ maskAuthOf,
+ tunnelBodyOf,
+ tunnelDirtyOf,
+ tunnelDraftOf,
+ tunnelMissingOf,
+} from './access-form'
+
+const stopped: AccessTunnel = { enabled: false, mode: 'quick', hostname: null, state: 'stopped', events: [] }
+
+describe('接入面板草稿与格式化', () => {
+ it('倒计时按 分:秒 渲染,过期与不足一秒都为空串', () => {
+ expect(countdownOf(1_000_000 + 300_000, 1_000_000)).toBe('5:00')
+ expect(countdownOf(1_000_000 + 65_000, 1_000_000)).toBe('1:05')
+ expect(countdownOf(1_000_000 + 400, 1_000_000)).toBe('')
+ expect(countdownOf(1_000_000, 1_000_000)).toBe('')
+ })
+
+ it('局域网草稿只在地址真的变了才算脏', () => {
+ expect(lanDirtyOf(null, { address: '192.168.1.5' })).toBe(false)
+ expect(lanDirtyOf({ address: '192.168.1.5' }, { address: '192.168.1.5' })).toBe(false)
+ expect(lanDirtyOf({ address: '127.0.0.1' }, { address: '192.168.1.5' })).toBe(true)
+ })
+
+ it('隧道草稿以已保存配置为基线,改回原值即不脏', () => {
+ const saved: AccessTunnel = { ...stopped, enabled: true, mode: 'token', token: 'cf', hostname: 'dsh.example.com' }
+ expect(tunnelDraftOf(saved)).toEqual({ mode: 'token', token: 'cf', hostname: 'dsh.example.com' })
+ expect(tunnelDraftOf(stopped)).toEqual({ mode: 'quick', token: null, hostname: '' })
+ expect(tunnelDirtyOf(null, saved)).toBe(false)
+ expect(tunnelDirtyOf(tunnelDraftOf(saved), saved)).toBe(false)
+ const edited = { ...tunnelDraftOf(saved), hostname: 'other.example.com' }
+ expect(tunnelDirtyOf(edited, saved)).toBe(true)
+ expect(tunnelDirtyOf({ ...tunnelDraftOf(saved), mode: 'quick' as const }, saved)).toBe(true)
+ })
+
+ it('具名模式缺必填项时指出缺哪一个,quick 模式不校验', () => {
+ expect(tunnelMissingOf({ mode: 'quick', token: null, hostname: '' })).toBeUndefined()
+ expect(tunnelMissingOf({ mode: 'token', token: null, hostname: 'dsh.example.com' })).toBe('token')
+ expect(tunnelMissingOf({ mode: 'token', token: ' ', hostname: 'dsh.example.com' })).toBe('token')
+ expect(tunnelMissingOf({ mode: 'token', token: 'cf', hostname: ' ' })).toBe('hostname')
+ expect(tunnelMissingOf({ mode: 'token', token: 'cf', hostname: 'dsh.example.com' })).toBeUndefined()
+ })
+
+ it('提交体从不提交空 Token 或空主机名,但会带出已保存的 Token', () => {
+ expect(tunnelBodyOf({ mode: 'quick', token: null, hostname: '' })).toEqual({ mode: 'quick' })
+ expect(tunnelBodyOf({ mode: 'token', token: 'cf', hostname: 'dsh.example.com' })).toEqual({
+ mode: 'token',
+ token: 'cf',
+ hostname: 'dsh.example.com',
+ })
+ expect(tunnelBodyOf({ mode: 'token', token: 'cf', hostname: '' })).toEqual({ mode: 'token', token: 'cf' })
+ })
+
+ it('永久码掩码只抹掉 auth 参数', () => {
+ expect(maskAuthOf('http://192.168.1.5:3088/?auth=tok')).toBe('http://192.168.1.5:3088/?auth=••••••')
+ expect(maskAuthOf('https://x.trycloudflare.com/?auth=tok&b=1')).toBe('https://x.trycloudflare.com/?auth=••••••&b=1')
+ expect(maskAuthOf('http://192.168.1.5:3088/')).toBe('http://192.168.1.5:3088/')
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/client/utils/access-form.ts b/packages/dsh-tauri-remote/src/client/utils/access-form.ts
new file mode 100644
index 00000000..b97eb48b
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/utils/access-form.ts
@@ -0,0 +1,57 @@
+import type { AccessTunnel, TunnelBody, TunnelMode } from '../types/index'
+
+export interface LanDraft {
+ address: string
+}
+
+export interface TunnelDraft {
+ mode: TunnelMode
+ token: string | null
+ hostname: string
+}
+
+export type TunnelField = 'token' | 'hostname'
+
+export function countdownOf(expiresAt: number, now: number): string {
+ const left = Math.floor((expiresAt - now) / 1000)
+ if (left <= 0)
+ return ''
+ return `${Math.floor(left / 60)}:${String(left % 60).padStart(2, '0')}`
+}
+
+export function lanDirtyOf(draft: LanDraft | null, listen: { address: string }): boolean {
+ return draft !== null && draft.address !== listen.address
+}
+
+export function tunnelDraftOf(tunnel: AccessTunnel): TunnelDraft {
+ return { mode: tunnel.mode, token: tunnel.token ?? null, hostname: tunnel.hostname ?? '' }
+}
+
+export function tunnelDirtyOf(draft: TunnelDraft | null, tunnel: AccessTunnel): boolean {
+ if (draft === null)
+ return false
+ const saved = tunnelDraftOf(tunnel)
+ return draft.mode !== saved.mode || draft.token !== saved.token || draft.hostname !== saved.hostname
+}
+
+export function tunnelMissingOf(draft: TunnelDraft): TunnelField | undefined {
+ if (draft.mode !== 'token')
+ return undefined
+ if (draft.token === null || draft.token.trim() === '')
+ return 'token'
+ return draft.hostname.trim() === '' ? 'hostname' : undefined
+}
+
+export function tunnelBodyOf(draft: TunnelDraft): TunnelBody {
+ const token = draft.token === null ? '' : draft.token.trim()
+ const hostname = draft.hostname.trim()
+ return {
+ mode: draft.mode,
+ ...token === '' ? {} : { token },
+ ...hostname === '' ? {} : { hostname },
+ }
+}
+
+export function maskAuthOf(link: string): string {
+ return link.replace(/([?&]auth=)[^&]*/, '$1••••••')
+}
diff --git a/packages/dsh-tauri-remote/src/client/utils/error.ts b/packages/dsh-tauri-remote/src/client/utils/error.ts
new file mode 100644
index 00000000..2d0fed1f
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/client/utils/error.ts
@@ -0,0 +1,6 @@
+import type { RemoteKey } from '../locales/index'
+import { isTransportError } from '../apis/parsers'
+
+export function errorTextOf(message: string, t: (key: RemoteKey) => string): string {
+ return isTransportError(message) ? t('error.unavailable') : message
+}
diff --git a/packages/dsh-tauri-ssh/src/client/utils/retry.test.ts b/packages/dsh-tauri-remote/src/client/utils/retry.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/client/utils/retry.test.ts
rename to packages/dsh-tauri-remote/src/client/utils/retry.test.ts
diff --git a/packages/dsh-tauri-ssh/src/client/utils/retry.ts b/packages/dsh-tauri-remote/src/client/utils/retry.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/client/utils/retry.ts
rename to packages/dsh-tauri-remote/src/client/utils/retry.ts
diff --git a/packages/dsh-tauri-ssh/src/host/apply.test.ts b/packages/dsh-tauri-remote/src/host/apply.test.ts
similarity index 55%
rename from packages/dsh-tauri-ssh/src/host/apply.test.ts
rename to packages/dsh-tauri-remote/src/host/apply.test.ts
index 51df34bc..fc84031d 100644
--- a/packages/dsh-tauri-ssh/src/host/apply.test.ts
+++ b/packages/dsh-tauri-remote/src/host/apply.test.ts
@@ -1,14 +1,42 @@
-import type { Config as SshRemoteConfig } from './config/schema'
-import type { SshHostContext } from './types/index'
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import type { AddressInfo } from 'node:net'
+import type { Config as RemoteConfig } from './config/schema'
+import type { RemoteHostContext } from './types/index'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { createServer } from 'node:net'
import { homedir, tmpdir } from 'node:os'
-import { join } from 'pathe'
+import { dirname, join } from 'pathe'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { apply, inject, name } from './apply'
-import { knownHostsFilePath, machineProfiles, resetRuntime } from './config/runtime'
+import { clearHostRuntime, knownHostsFilePath, machineProfiles, migrateLegacyState, migrationWarningOf } from './config/runtime'
+import { gateway } from './service/gateway'
+import { readHostKeyRecords } from './service/known-hosts.utils'
import { machine } from './service/machine'
import { MachineId } from './types/index'
+function freePort(): Promise<{ port: number, release: () => Promise<void> }> {
+ const server = createServer()
+ return new Promise((resolve) => {
+ server.listen(0, '127.0.0.1', () => {
+ const port = (server.address() as AddressInfo).port
+ resolve({ port, release: () => new Promise<void>((done) => {
+ server.close(() => done())
+ }) })
+ })
+ })
+}
+
+function freePortAt(port: number): Promise<{ port: number, release: () => Promise<void> } | undefined> {
+ const server = createServer()
+ return new Promise((resolve) => {
+ server.once('error', () => resolve(undefined))
+ server.listen(port, '127.0.0.1', () => {
+ resolve({ port, release: () => new Promise<void>((done) => {
+ server.close(() => done())
+ }) })
+ })
+ })
+}
+
function scriptedHttpServer() {
const routes: Array<{ kind: string, path: string, handler?: unknown }> = []
return {
@@ -20,21 +48,23 @@ function scriptedHttpServer() {
}
}
+const BASE = '/api/tauri/remote'
+
const REST_ENDPOINTS = [
- '/api/tauri/ssh/settings',
- '/api/tauri/ssh/session/role',
- '/api/tauri/ssh/machines',
- '/api/tauri/ssh/machines/test',
- '/api/tauri/ssh/machines/connect',
- '/api/tauri/ssh/machines/disconnect',
- '/api/tauri/ssh/machines/install',
- '/api/tauri/ssh/machines/events',
- '/api/tauri/ssh/sync/preview',
- '/api/tauri/ssh/sync/apply',
+ '/api/tauri/remote/settings',
+ '/api/tauri/remote/session/role',
+ '/api/tauri/remote/machines',
+ '/api/tauri/remote/machines/test',
+ '/api/tauri/remote/machines/connect',
+ '/api/tauri/remote/machines/disconnect',
+ '/api/tauri/remote/machines/install',
+ '/api/tauri/remote/machines/events',
+ '/api/tauri/remote/sync/preview',
+ '/api/tauri/remote/sync/apply',
]
/** Plugin config without the optional overrides; defaults are exercised separately. */
-const baseConfig: SshRemoteConfig = {
+const baseConfig: RemoteConfig = {
connectTimeoutMs: 15000,
healthCheckTimeoutMs: 1000,
healthPollIntervalMs: 5,
@@ -51,21 +81,29 @@ const baseConfig: SshRemoteConfig = {
// harness home are never touched.
let sshDir: string
let statePath: string
+let previousHome: string | undefined
beforeEach(() => {
- resetRuntime()
+ clearHostRuntime()
sshDir = mkdtempSync(join(tmpdir(), 'ssh-index-'))
statePath = join(sshDir, 'machines.json')
+ // 暴露配置也落在 $DSH_HOME 下:不隔离就会读到(并在 enabled 时真的开启)开发机上的真实配置。
+ previousHome = process.env.DSH_HOME
+ process.env.DSH_HOME = sshDir
})
afterEach(() => {
vi.restoreAllMocks()
+ if (previousHome === undefined)
+ delete process.env.DSH_HOME
+ else
+ process.env.DSH_HOME = previousHome
rmSync(sshDir, { recursive: true, force: true })
- resetRuntime()
+ clearHostRuntime()
})
/** One scripted context: cordis-shaped surface without real cordis types. */
-function scriptedCtx(webServer: unknown): { ctx: SshHostContext, disposers: Array<() => void> } {
+function scriptedCtx(webServer: unknown, logger?: RemoteHostContext['logger']): { ctx: RemoteHostContext, disposers: Array<() => void> } {
const disposers: Array<() => void> = []
const ctx = {
provide: vi.fn(),
@@ -74,8 +112,9 @@ function scriptedCtx(webServer: unknown): { ctx: SshHostContext, disposers: Arra
if (typeof disposer === 'function')
disposers.push(disposer)
}),
+ ...logger === undefined ? {} : { logger },
webServer,
- } as unknown as SshHostContext
+ } as unknown as RemoteHostContext
return { ctx, disposers }
}
@@ -90,7 +129,7 @@ function readState(): { version: number, enabled: boolean, machines: Record<stri
}
/** Assemble the plugin on a scripted webServer double. */
-function construct(config: SshRemoteConfig = baseConfig, webServer = scriptedHttpServer()): { ctx: SshHostContext, webServer: ReturnType<typeof scriptedHttpServer>, service: typeof machine, disposers: Array<() => void> } {
+function construct(config: RemoteConfig = baseConfig, webServer = scriptedHttpServer()): { ctx: RemoteHostContext, webServer: ReturnType<typeof scriptedHttpServer>, service: typeof machine, disposers: Array<() => void> } {
const { ctx, disposers } = scriptedCtx(webServer)
apply(ctx, { ...config, sshDir, statePath })
return { ctx, webServer, service: machine, disposers }
@@ -99,7 +138,7 @@ function construct(config: SshRemoteConfig = baseConfig, webServer = scriptedHtt
async function boot(overrides: {
state?: { enabled?: boolean, machines?: Record<string, unknown> }
webServer?: ReturnType<typeof scriptedHttpServer>
- config?: Partial<SshRemoteConfig>
+ config?: Partial<RemoteConfig>
} = {}) {
if (overrides.state !== undefined)
writeState(overrides.state)
@@ -129,9 +168,9 @@ function row(id: string): Record<string, unknown> {
}
}
-describe('ssh-remote plugin', () => {
+describe('remote plugin', () => {
it('declares its plugin metadata', () => {
- expect(name).toBe('dsh-tauri-ssh')
+ expect(name).toBe('dsh-tauri-remote')
expect(inject).toEqual(['webServer', 'connection'])
expect(apply).toEqual(expect.any(Function))
})
@@ -139,7 +178,7 @@ describe('ssh-remote plugin', () => {
it('ships the cordis plugin descriptor as the default export', async () => {
const descriptor = (await import('./apply')).default
expect(descriptor).toMatchObject({
- name: 'dsh-tauri-ssh',
+ name: 'dsh-tauri-remote',
inject: ['webServer', 'connection'],
Config: expect.anything(),
})
@@ -151,8 +190,20 @@ describe('ssh-remote plugin', () => {
it('mounts the REST routes without any settings service', async () => {
const { webServer } = await boot()
- expect(webServer.routes.map(route => `${route.kind} ${route.path}`)).toEqual(REST_ENDPOINTS.map(path => `exact ${path}`))
- expect(webServer.routes.map(route => typeof route.handler)).toEqual(REST_ENDPOINTS.map(() => 'function'))
+ const management = webServer.routes.filter(route => !route.path.includes('/access'))
+ expect(management.map(route => `${route.kind} ${route.path}`)).toEqual(REST_ENDPOINTS.map(path => `exact ${path}`))
+ expect(management.map(route => typeof route.handler)).toEqual(REST_ENDPOINTS.map(() => 'function'))
+ })
+
+ it('mounts the sharing and credential access routes on the same host', async () => {
+ const { webServer } = await boot()
+ const panelRoutes = webServer.routes.filter(route => route.path.includes('/access'))
+ expect(panelRoutes.map(route => `${route.kind} ${route.path}`)).toEqual([
+ `exact ${BASE}/access`,
+ `exact ${BASE}/access/tunnel`,
+ `exact ${BASE}/access/token`,
+ ])
+ expect(panelRoutes.map(route => typeof route.handler)).toEqual(['function', 'function', 'function'])
})
it('starts switched off and persists the enable switch', async () => {
@@ -440,9 +491,9 @@ describe('ssh-remote plugin', () => {
process.env.DSH_HOME = home
apply(scriptedCtx(scriptedHttpServer()).ctx, { ...baseConfig, sshDir })
await machine.start()
- expect(knownHostsFilePath()).toBe(join(home, 'ssh', 'known-hosts.json'))
+ expect(knownHostsFilePath()).toBe(join(home, 'remote', 'known-hosts.json'))
await machine.setEnabled(true)
- expect(JSON.parse(readFileSync(join(home, 'ssh', 'machines.json'), 'utf8'))).toMatchObject({ version: 1, enabled: true })
+ expect(JSON.parse(readFileSync(join(home, 'remote', 'machines.json'), 'utf8'))).toMatchObject({ version: 1, enabled: true })
}
finally {
if (previous === undefined)
@@ -452,17 +503,219 @@ describe('ssh-remote plugin', () => {
}
})
+ it('清理串行:dispose 期间运行时依赖仍可用,全部落定后才清空', async () => {
+ const { service, disposers } = construct()
+ const { machineRuntimeDeps } = await import('./config/runtime')
+ let during = ''
+ vi.spyOn(service, 'dispose').mockImplementation(async () => {
+ try {
+ machineRuntimeDeps()
+ during = 'available'
+ }
+ catch {
+ during = 'cleared'
+ }
+ })
+ for (const disposeAll of disposers) disposeAll()
+ await vi.waitFor(() => {
+ expect(during).not.toBe('')
+ })
+ expect(during, 'dispose 期间不得提前清空依赖').toBe('available')
+ await vi.waitFor(() => {
+ expect(() => machineRuntimeDeps()).toThrow()
+ })
+ })
+
it('disposes the manager when the context tears down', () => {
const { service, disposers } = construct()
const dispose = vi.spyOn(service, 'dispose').mockResolvedValue(undefined)
- expect(disposers).toHaveLength(2)
+ expect(disposers).toHaveLength(3)
for (const disposeAll of disposers) disposeAll()
expect(dispose).toHaveBeenCalledTimes(1)
})
+ it('closes every gateway entry and releases its port when the context tears down', async () => {
+ const { disposers } = construct()
+ const free = await freePort()
+ const port = free.port
+ await free.release()
+ const status = await gateway.start({ id: 'entry', kind: 'inbound', upstream: 'http://127.0.0.1:1', port })
+ expect(status.port).toBe(port)
+ expect(status.state).toBe('listening')
+ for (const disposeAll of disposers) disposeAll()
+ await vi.waitFor(() => expect(gateway.status('entry')).toBeUndefined())
+ const rebound = await freePortAt(port)
+ expect(rebound).toBeDefined()
+ await rebound?.release()
+ })
+
it('assembles the plugin declaratively', () => {
const { ctx, webServer } = construct()
- expect(webServer.routes.map(route => `${route.kind} ${route.path}`)).toEqual(REST_ENDPOINTS.map(path => `exact ${path}`))
+ expect(webServer.routes.map(route => route.path)).toEqual(
+ expect.arrayContaining([...REST_ENDPOINTS, `${BASE}/access`, `${BASE}/access/token`]),
+ )
expect(apply(ctx, { ...baseConfig, sshDir, statePath })).toBeUndefined()
})
})
+
+describe('stored transport rows', () => {
+ it('reads a stored ssh transport as the default and never writes the key back', async () => {
+ const { service } = await boot({ state: { enabled: true, machines: { a: { ...row('a'), transport: 'ssh' } } } })
+ const profile = machineProfiles.get(MachineId('a'))
+ expect(profile).toMatchObject({ id: 'a', name: 'machine-a' })
+ expect(profile).not.toHaveProperty('transport')
+ await service.save(MachineId('a'), { name: 'alpha-2', host: '10.0.0.1', port: 22, user: 'root', remotePort: 3080 })
+ expect(readState().machines.a).not.toHaveProperty('transport')
+ })
+})
+
+/** 旧状态目录下的文档路径(迁移源)。 */
+function legacyDocument(home: string, file: string): string {
+ return join(home, 'ssh', file)
+}
+
+/** 新状态目录下的文档路径(迁移目标)。 */
+function stateDocument(home: string, file: string): string {
+ return join(home, 'remote', file)
+}
+
+function writeDocument(file: string, document: unknown): void {
+ mkdirSync(dirname(file), { recursive: true })
+ writeFileSync(file, `${JSON.stringify(document, null, 2)}\n`)
+}
+
+/** 像真实档案那样只用 DSH_HOME 定位状态:不传 statePath / knownHostsPath,迁移才会触发。 */
+async function bootWithHome(home: string, logger: RemoteHostContext['logger']): Promise<typeof machine> {
+ const previous = process.env.DSH_HOME
+ process.env.DSH_HOME = home
+ try {
+ const { ctx } = scriptedCtx(scriptedHttpServer(), logger)
+ apply(ctx, { ...baseConfig, sshDir })
+ await machine.start()
+ }
+ finally {
+ if (previous === undefined)
+ delete process.env.DSH_HOME
+ else
+ process.env.DSH_HOME = previous
+ }
+ return machine
+}
+
+function quietLogger(): { error: (message: string) => void, warn: (message: string) => void } {
+ return { error: () => {}, warn: vi.fn<(message: string) => void>() }
+}
+
+/** 记下的告警文案(迁移只在未完成时写 warn,因此它就是迁移结论)。 */
+function warnedMessages(logger: { warn: (message: string) => void }): string[] {
+ return vi.mocked(logger.warn).mock.calls.map(call => String(call[0]))
+}
+
+describe('state directory migration', () => {
+ it('carries machines and known-hosts over while leaving the legacy files in place', async () => {
+ const home = join(sshDir, 'legacy-home')
+ writeDocument(legacyDocument(home, 'machines.json'), { version: 1, enabled: true, machines: { a: row('a') } })
+ writeDocument(legacyDocument(home, 'known-hosts.json'), [{ machineId: 'a', fingerprint: 'SHA256:legacy' }])
+ const legacyState = readFileSync(legacyDocument(home, 'machines.json'), 'utf8')
+ const legacyHosts = readFileSync(legacyDocument(home, 'known-hosts.json'), 'utf8')
+ const logger = quietLogger()
+
+ const service = await bootWithHome(home, logger)
+ expect(service.enabled()).toBe(true)
+ expect(service.profileViews().map(view => view.id)).toEqual(['a'])
+ await expect(readHostKeyRecords(stateDocument(home, 'known-hosts.json'))).resolves.toEqual([{ machineId: 'a', fingerprint: 'SHA256:legacy' }])
+ expect(readFileSync(legacyDocument(home, 'machines.json'), 'utf8')).toBe(legacyState)
+ expect(readFileSync(legacyDocument(home, 'known-hosts.json'), 'utf8')).toBe(legacyHosts)
+ expect(warnedMessages(logger)).toEqual([])
+ expect(migrateLegacyState()).toBeUndefined()
+ expect(readFileSync(stateDocument(home, 'machines.json'), 'utf8')).toBe(`${JSON.stringify({ version: 1, enabled: true, machines: { a: row('a') } }, null, 2)}\n`)
+ })
+
+ it('prefers an existing target document and never rewrites it', async () => {
+ const home = join(sshDir, 'existing-home')
+ writeDocument(legacyDocument(home, 'machines.json'), { version: 1, enabled: true, machines: { legacy: row('legacy') } })
+ writeDocument(stateDocument(home, 'machines.json'), { version: 1, enabled: true, machines: { current: row('current') } })
+ const current = readFileSync(stateDocument(home, 'machines.json'), 'utf8')
+ const logger = quietLogger()
+
+ const service = await bootWithHome(home, logger)
+ expect(service.profileViews().map(view => view.id)).toEqual(['current'])
+ expect(readFileSync(stateDocument(home, 'machines.json'), 'utf8')).toBe(current)
+ expect(existsSync(legacyDocument(home, 'machines.json'))).toBe(true)
+ expect(warnedMessages(logger)).toEqual([])
+ })
+
+ it('treats an empty target document as already migrated and starts from the default state', async () => {
+ const home = join(sshDir, 'half-migrated-home')
+ writeDocument(legacyDocument(home, 'machines.json'), { version: 1, enabled: true, machines: { a: row('a') } })
+ mkdirSync(dirname(stateDocument(home, 'machines.json')), { recursive: true })
+ writeFileSync(stateDocument(home, 'machines.json'), '')
+ const logger = quietLogger()
+
+ const service = await bootWithHome(home, logger)
+ expect(service.profileViews()).toEqual([])
+ expect(readFileSync(stateDocument(home, 'machines.json'), 'utf8')).toBe('')
+ expect(warnedMessages(logger)).toEqual([])
+ })
+
+ it('warns instead of failing when the legacy document is corrupt, then accepts new machines', async () => {
+ const home = join(sshDir, 'corrupt-home')
+ mkdirSync(dirname(legacyDocument(home, 'machines.json')), { recursive: true })
+ writeFileSync(legacyDocument(home, 'machines.json'), '{ not json')
+ writeDocument(legacyDocument(home, 'known-hosts.json'), [{ machineId: 'a', fingerprint: 'SHA256:legacy' }])
+ const logger = quietLogger()
+
+ const service = await bootWithHome(home, logger)
+ expect(service.profileViews()).toEqual([])
+ expect(warnedMessages(logger)).toHaveLength(1)
+ expect(warnedMessages(logger)[0]).toContain('旧状态目录迁移未完成')
+ expect(warnedMessages(logger)[0]).toContain('不是合法 JSON')
+ expect(migrationWarningOf()).toContain('不是合法 JSON')
+ await expect(readHostKeyRecords(stateDocument(home, 'known-hosts.json'))).resolves.toEqual([{ machineId: 'a', fingerprint: 'SHA256:legacy' }])
+ await service.save(MachineId('c'), { name: 'gamma', host: '10.0.0.3', port: 22, user: 'root', remotePort: 3080 })
+ expect(service.profileViews().map(view => view.id)).toEqual(['c'])
+ expect(existsSync(legacyDocument(home, 'machines.json'))).toBe(true)
+ })
+
+ it('warns instead of failing when the new state directory cannot be created, then starts empty', async () => {
+ const home = join(sshDir, 'blocked-home')
+ writeDocument(legacyDocument(home, 'machines.json'), { version: 1, enabled: true, machines: { a: row('a') } })
+ writeDocument(legacyDocument(home, 'known-hosts.json'), [{ machineId: 'a', fingerprint: 'SHA256:legacy' }])
+ const legacyState = readFileSync(legacyDocument(home, 'machines.json'), 'utf8')
+ const legacyHosts = readFileSync(legacyDocument(home, 'known-hosts.json'), 'utf8')
+ writeFileSync(join(home, 'remote'), 'blocked')
+ const logger = quietLogger()
+
+ const service = await bootWithHome(home, logger)
+ expect(service.enabled()).toBe(false)
+ expect(service.profileViews()).toEqual([])
+ expect(warnedMessages(logger)).toHaveLength(1)
+ expect(warnedMessages(logger)[0]).toContain('旧状态目录迁移未完成')
+ expect(warnedMessages(logger)[0]).toContain(migrationWarningOf())
+ expect(migrationWarningOf()).toContain('mkdir')
+ expect(migrateLegacyState()).toBe(migrationWarningOf())
+ expect(readFileSync(legacyDocument(home, 'machines.json'), 'utf8')).toBe(legacyState)
+ expect(readFileSync(legacyDocument(home, 'known-hosts.json'), 'utf8')).toBe(legacyHosts)
+ })
+
+ it('skips migration entirely when the state paths are configured explicitly', async () => {
+ const home = join(sshDir, 'configured-home')
+ writeDocument(legacyDocument(home, 'machines.json'), { version: 1, enabled: true, machines: { a: row('a') } })
+ const previous = process.env.DSH_HOME
+ process.env.DSH_HOME = home
+ try {
+ apply(scriptedCtx(scriptedHttpServer()).ctx, { ...baseConfig, sshDir, knownHostsPath: join(sshDir, 'known-hosts.json'), statePath })
+ await machine.start()
+ expect(machine.profileViews()).toEqual([])
+ await machine.setEnabled(true)
+ expect(JSON.parse(readFileSync(statePath, 'utf8'))).toMatchObject({ version: 1, enabled: true })
+ expect(existsSync(stateDocument(home, 'machines.json'))).toBe(false)
+ }
+ finally {
+ if (previous === undefined)
+ delete process.env.DSH_HOME
+ else
+ process.env.DSH_HOME = previous
+ }
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/host/apply.ts b/packages/dsh-tauri-remote/src/host/apply.ts
new file mode 100644
index 00000000..70a58288
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/apply.ts
@@ -0,0 +1,95 @@
+import type { Context } from '@deepseek-ai/cordis'
+import type z from 'schemastery'
+import type { Config as RemoteConfig } from './config/schema'
+import type { RemoteHostContext } from './types/index'
+import { REMOTE_PLUGIN_NAME } from '../shared/constants'
+import { clearHostRuntime, migrateLegacyState, setCurrentHostInstance, setHostConfig, setMachineDeps, setSyncDeps, setTunnelDeps } from './config/runtime'
+import { ConfigSchema } from './config/schema'
+import { server } from './server'
+import { panel } from './server/panel'
+import { access } from './service/access'
+import { gateway } from './service/gateway'
+import { machine } from './service/machine'
+import { transport } from './service/transport'
+import { tunnel } from './service/tunnel'
+import { resolveCloudflared, spawnCloudflared } from './utils/cloudflared'
+import { packSkills, profileAllowlistReader, profileDependenciesReader, skillRootsScanner } from './utils/local'
+
+const REMOTE_START_EFFECT = `${REMOTE_PLUGIN_NAME}: start`
+
+const REMOTE_ROUTES_EFFECT = `${REMOTE_PLUGIN_NAME}: routes`
+
+const REMOTE_PANEL_EFFECT = `${REMOTE_PLUGIN_NAME}: panel routes`
+
+const REMOTE_RUNTIME_EFFECT = `${REMOTE_PLUGIN_NAME}: host runtime`
+
+export const name = REMOTE_PLUGIN_NAME
+
+export const inject = ['webServer', 'connection']
+
+export const Config: z<RemoteConfig> = ConfigSchema
+
+export function apply(ctx: RemoteHostContext, config: RemoteConfig): void {
+ setCurrentHostInstance(ctx)
+ setHostConfig(config)
+ setMachineDeps({
+ transport,
+ emitStatus: () => {}, // keep: 进度出口注入点,故意留空——状态另经 status() 与事件环读取
+ localAllowlist: profileAllowlistReader(),
+ })
+ setSyncDeps({
+ profileDependencies: profileDependenciesReader(),
+ scanSkills: skillRootsScanner(),
+ packSkills,
+ ...config.installTimeoutMs === undefined ? {} : { commandTimeoutMs: config.installTimeoutMs },
+ })
+ setTunnelDeps({
+ policy: () => access.policy(),
+ resolveBinary: resolveCloudflared,
+ spawn: spawnCloudflared,
+ })
+
+ ctx.effect(() => {
+ const migrationFailure = migrateLegacyState()
+ if (migrationFailure !== undefined)
+ ctx.logger?.warn?.(`${REMOTE_PLUGIN_NAME}: 旧状态目录迁移未完成,已按新目录空状态启动(旧文件未改动): ${migrationFailure}`)
+ void machine.start().catch(() => undefined)
+ void access.restore().catch(() => undefined)
+ void tunnel.restore().catch(() => undefined)
+ }, REMOTE_START_EFFECT)
+
+ ctx.effect(() => server(ctx as unknown as Context), REMOTE_ROUTES_EFFECT)
+
+ ctx.effect(() => panel(ctx as unknown as Context), REMOTE_PANEL_EFFECT)
+
+ ctx.effect(() => () => {
+ // keep: 清理要串行等待:先让各服务停监听、回收子进程,最后才清运行时依赖
+ // (提前清空会让在途 dispose 读不到 deps,清理静默失败)
+ void shutdown().catch((error: unknown) => {
+ ctx.logger?.error?.(`${REMOTE_PLUGIN_NAME}: 关闭清理失败: ${error instanceof Error ? error.message : String(error)}`)
+ })
+ }, REMOTE_RUNTIME_EFFECT)
+}
+
+export default { apply, Config, inject, name }
+
+// --- internal ---
+async function shutdown(): Promise<void> {
+ try {
+ await machine.dispose()
+ }
+ finally {
+ try {
+ await tunnel.dispose()
+ }
+ finally {
+ try {
+ await access.dispose()
+ }
+ finally {
+ await gateway.dispose().catch(() => undefined)
+ clearHostRuntime()
+ }
+ }
+ }
+}
diff --git a/packages/dsh-tauri-remote/src/host/config/constants.ts b/packages/dsh-tauri-remote/src/host/config/constants.ts
new file mode 100644
index 00000000..d07c6e7f
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/config/constants.ts
@@ -0,0 +1,12 @@
+export const EVENT_RING_CAPACITY = 500
+
+export const DEFAULT_REMOTE_PROFILE = 'remote'
+
+export const DEFAULT_MACHINE_TRANSPORT = 'ssh'
+
+export const REMOTE_ROOT = '.dsh-desktop'
+
+/** 内部来源标识的两枚头名(S2 §9);网关注入侧与插件判定侧必须逐字一致。 */
+export const GATEWAY_SOURCE_HEADER = 'x-dsh-remote-source'
+
+export const GATEWAY_SESSION_HEADER = 'x-dsh-remote-session'
diff --git a/packages/dsh-tauri-remote/src/host/config/runtime.ts b/packages/dsh-tauri-remote/src/host/config/runtime.ts
new file mode 100644
index 00000000..416064a4
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/config/runtime.ts
@@ -0,0 +1,262 @@
+import type { MachineDeps, MachineState } from '../service/machine.types'
+import type { SyncDeps } from '../service/sync.types'
+import type { TunnelDeps } from '../service/tunnel.types'
+import type { MachineId, MachineProfile, RemoteHostContext, RemoteMachineEvent } from '../types/index'
+import type { Config } from './schema'
+import { randomBytes } from 'node:crypto'
+import { homedir } from 'node:os'
+import process from 'node:process'
+import { join } from 'pathe'
+import { messageOf } from '../../shared/error'
+import { migrateDocument } from '../utils/migrate'
+import { EVENT_RING_CAPACITY } from './constants'
+
+const STATE_DIR = 'remote'
+const LEGACY_STATE_DIR = 'ssh'
+const STATE_DOCUMENT = 'machines.json'
+const KNOWN_HOSTS_DOCUMENT = 'known-hosts.json'
+const ACCESS_DOCUMENT = 'access.json'
+
+let hostInstance: RemoteHostContext | undefined
+
+export function setCurrentHostInstance(next: RemoteHostContext | undefined): void {
+ hostInstance = next
+}
+
+export function getCurrentHostInstance(): RemoteHostContext {
+ if (hostInstance === undefined)
+ throw new TypeError('getCurrentHostInstance: 宿主实例尚未绑定,apply.ts 需先调用 setCurrentHostInstance(ctx)')
+ return hostInstance
+}
+
+export const machineProfiles = new Map<MachineId, MachineProfile>()
+
+export const machineStates = new Map<MachineId, MachineState>()
+
+export const machineTable: { enabled: boolean, machines: Map<MachineId, MachineProfile> } = {
+ enabled: false,
+ machines: new Map(),
+}
+
+export const eventBuffers = new Map<MachineId, { seq: number, events: RemoteMachineEvent[] }>()
+
+let config: Config | undefined
+let homeDir = homedir()
+let sshDir = ''
+let statePath = ''
+let knownHostsPath = ''
+let eventCapacity = EVENT_RING_CAPACITY
+let deps: MachineDeps | undefined
+let syncDeps: SyncDeps | undefined
+let tunnelDeps: TunnelDeps | undefined
+let migrated = false
+let migrationWarning: string | undefined
+let sourceSession = ''
+
+export function setSourceSession(session: string): void {
+ sourceSession = session
+}
+
+/** 网关装配时的会话标识保证:未设置则生成一次进程内随机值,注入与判定两侧共用同一枚。 */
+export function ensureSourceSession(): string {
+ if (sourceSession === '')
+ sourceSession = randomBytes(32).toString('hex')
+ return sourceSession
+}
+
+/** 网关进程内会话标识:只有持有它的转发请求才能声明来源分类(未设置时任何声明都不可信)。 */
+export function sourceSessionToken(): string {
+ return sourceSession
+}
+
+export function harnessHome(): string {
+ return process.env.DSH_HOME ?? join(homedir(), '.dsh')
+}
+
+function stateDir(): string {
+ return join(harnessHome(), STATE_DIR)
+}
+
+function legacyStateDir(): string {
+ return join(harnessHome(), LEGACY_STATE_DIR)
+}
+
+export function hostConfig(): Config {
+ if (config === undefined)
+ throw new TypeError('hostConfig: 插件配置尚未装配,apply.ts 需先调用 setHostConfig(config)')
+ return config
+}
+
+export function setHostConfig(next: Config): void {
+ config = next
+ homeDir = homedir()
+ sshDir = next.sshDir ?? join(homeDir, '.ssh')
+ statePath = next.statePath ?? join(stateDir(), STATE_DOCUMENT)
+ knownHostsPath = next.knownHostsPath ?? join(stateDir(), KNOWN_HOSTS_DOCUMENT)
+}
+
+export function stateDocumentPath(): string {
+ return statePath === '' ? join(stateDir(), STATE_DOCUMENT) : statePath
+}
+
+export function setKnownHostsPath(path: string): void {
+ knownHostsPath = path
+}
+
+export function knownHostsFilePath(): string {
+ return knownHostsPath === '' ? join(stateDir(), KNOWN_HOSTS_DOCUMENT) : knownHostsPath
+}
+
+export function accessDocumentPath(): string {
+ return join(stateDir(), ACCESS_DOCUMENT)
+}
+
+/** 本机 DSH 服务端口:宿主 webserver 的实监听端口优先,`DSH_WEB_PORT` 仅作回退(非桌面载体没有该变量)。 */
+export function hostServicePort(): number | undefined {
+ try {
+ const port = getCurrentHostInstance().webServer.port
+ if (isServicePort(port))
+ return port
+ }
+ catch {
+ // keep: 宿主实例可能尚未绑定(或已随插件卸载清空),回退进程环境变量
+ }
+ const fallback = Number(process.env.DSH_WEB_PORT)
+ return isServicePort(fallback) ? fallback : undefined
+}
+
+export function localUpstream(): string | undefined {
+ const port = hostServicePort()
+ return port === undefined ? undefined : `http://127.0.0.1:${port}`
+}
+
+/** 上游 authority 绑定凭据的铸造:宿主实例尚未绑定(或已随插件卸载清空)时放弃本次铸造,不阻断转发。 */
+export async function mintAuthenticatedUrl(authority: string): Promise<string | undefined> {
+ try {
+ return await getCurrentHostInstance().connection?.authenticatedUrl(`http://${authority}/`)
+ }
+ catch {
+ return undefined
+ }
+}
+
+function isServicePort(port: unknown): port is number {
+ return typeof port === 'number' && Number.isInteger(port) && port > 0 && port <= 65535
+}
+
+/**
+ * 一次性幂等迁移 `$DSH_HOME/ssh/` → `$DSH_HOME/remote/`:进程内去重、旧文件保留为只读备份、
+ * 目标已存在(含半迁移的空文件)即视为已迁移,失败只回可读原因、绝不阻断插件加载。
+ *
+ * @returns 未迁移原因(旧文件损坏 / 写入失败);全部成功或无需迁移时为 undefined。
+ */
+export function migrateLegacyState(): string | undefined {
+ if (migrated)
+ return migrationWarning
+ migrated = true
+ const reasons: string[] = []
+ let current: Config
+ try {
+ current = hostConfig()
+ }
+ catch (error) {
+ migrationWarning = messageOf(error)
+ return migrationWarning
+ }
+ // 两份文档各自迁移:其中一份损坏或写不进去,不影响另一份被带过来。
+ if (current.statePath === undefined)
+ migrateInto(join(legacyStateDir(), STATE_DOCUMENT), stateDocumentPath(), reasons)
+ if (current.knownHostsPath === undefined)
+ migrateInto(join(legacyStateDir(), KNOWN_HOSTS_DOCUMENT), knownHostsFilePath(), reasons)
+ migrationWarning = reasons.length === 0 ? undefined : reasons.join('; ')
+ return migrationWarning
+}
+
+/** 迁移失败原因(面板经 `GET /settings` 展示的那一条告警);成功或无需迁移时为 undefined。 */
+export function migrationWarningOf(): string | undefined {
+ return migrationWarning
+}
+
+export function setMigrationWarning(warning: string | undefined): void {
+ migrationWarning = warning
+}
+
+function migrateInto(source: string, target: string, reasons: string[]): void {
+ try {
+ migrateDocument(source, target)
+ }
+ catch (error) {
+ reasons.push(messageOf(error))
+ }
+}
+
+export function sshDirPath(): string {
+ return sshDir === '' ? join(homedir(), '.ssh') : sshDir
+}
+
+export function homeDirPath(): string {
+ return homeDir
+}
+
+export function setEventCapacity(capacity: number): void {
+ eventCapacity = capacity
+}
+
+export function eventRingCapacity(): number {
+ return eventCapacity
+}
+
+export function setMachineDeps(next: MachineDeps): void {
+ deps = next
+}
+
+export function machineRuntimeDeps(): MachineDeps {
+ if (deps === undefined)
+ throw new TypeError('machineRuntimeDeps: 连接面依赖尚未装配,apply.ts 需先调用 setMachineDeps(deps)')
+ return deps
+}
+
+export function setSyncDeps(next: SyncDeps): void {
+ syncDeps = next
+}
+
+export function syncRuntimeDeps(): SyncDeps {
+ if (syncDeps === undefined)
+ throw new TypeError('syncRuntimeDeps: 同步面依赖尚未装配,apply.ts 需先调用 setSyncDeps(deps)')
+ return syncDeps
+}
+
+export function setTunnelDeps(next: TunnelDeps): void {
+ tunnelDeps = next
+}
+
+export function tunnelRuntimeDeps(): TunnelDeps {
+ if (tunnelDeps === undefined)
+ throw new TypeError('tunnelRuntimeDeps: 隧道面依赖尚未装配,apply.ts 需先调用 setTunnelDeps(deps)')
+ return tunnelDeps
+}
+
+export function clearHostRuntime(): void {
+ // 使在途 attempt 失效:未完成的 performConnect/performInstall 恢复执行时会比对 generation,
+ // 若不等则不再对外拨号(否则它们的续跑会读到下一个 runtime 的 deps,把连接打到别人的 transport 上)。
+ for (const target of machineStates.values())
+ target.generation += 1
+ config = undefined
+ homeDir = homedir()
+ sshDir = ''
+ statePath = ''
+ knownHostsPath = ''
+ eventCapacity = EVENT_RING_CAPACITY
+ deps = undefined
+ syncDeps = undefined
+ tunnelDeps = undefined
+ migrated = false
+ migrationWarning = undefined
+ sourceSession = ''
+ machineProfiles.clear()
+ machineStates.clear()
+ machineTable.enabled = false
+ machineTable.machines.clear()
+ eventBuffers.clear()
+ setCurrentHostInstance(undefined)
+}
diff --git a/packages/dsh-tauri-ssh/src/host/config/schema.ts b/packages/dsh-tauri-remote/src/host/config/schema.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/config/schema.ts
rename to packages/dsh-tauri-remote/src/host/config/schema.ts
diff --git a/packages/dsh-tauri-ssh/src/host/server/index.test.ts b/packages/dsh-tauri-remote/src/host/server/index.test.ts
similarity index 70%
rename from packages/dsh-tauri-ssh/src/host/server/index.test.ts
rename to packages/dsh-tauri-remote/src/host/server/index.test.ts
index b33aa651..a77832a6 100644
--- a/packages/dsh-tauri-ssh/src/host/server/index.test.ts
+++ b/packages/dsh-tauri-remote/src/host/server/index.test.ts
@@ -1,15 +1,20 @@
-import type { HostWebRoute, MachineView, SshMachineStatus, SshTestResult, SyncPreview } from '../types/index'
-import type { SshActionResponse, SshConnectResponse, SshInstallResponse, SshMachineEventsResponse, SshMachinesResponse, SshSessionRoleResponse, SshSettingsResponse, SshTestResponse, SyncApplyResponse, SyncPreviewResponse } from './routes/index.types'
+import type { HostWebRoute, MachineView, RemoteMachineStatus, RemoteTestResult, SyncPreview } from '../types/index'
+import type { RemoteActionResponse, RemoteConnectResponse, RemoteInstallResponse, RemoteMachineEventsResponse, RemoteMachinesResponse, RemoteSessionRoleResponse, RemoteSettingsResponse, RemoteTestResponse, SyncApplyResponse, SyncPreviewResponse } from './routes/index.types'
import { createServer } from 'node:http'
-import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { GATEWAY_SESSION_HEADER, GATEWAY_SOURCE_HEADER } from '../config/constants'
+import { ensureSourceSession } from '../config/runtime'
+import { access } from '../service/access'
import { events } from '../service/events'
import { machine } from '../service/machine'
import { session } from '../service/session'
import { sync } from '../service/sync'
-import { MachineId, SshError } from '../types/index'
+import { tunnel } from '../service/tunnel'
+import { MachineId, RemoteError } from '../types/index'
import { server } from './index'
+import { LOOPBACK_ONLY_ERROR } from './panel.utils'
-const BASE = '/api/tauri/ssh'
+const BASE = '/api/tauri/remote'
const PATHS = [
`${BASE}/settings`,
@@ -22,6 +27,8 @@ const PATHS = [
`${BASE}/machines/events`,
`${BASE}/sync/preview`,
`${BASE}/sync/apply`,
+ `${BASE}/access`,
+ `${BASE}/access/tunnel`,
]
const ALLOW: Record<string, string> = {
@@ -35,6 +42,8 @@ const ALLOW: Record<string, string> = {
[`${BASE}/machines/events`]: 'GET, HEAD',
[`${BASE}/sync/preview`]: 'GET, HEAD',
[`${BASE}/sync/apply`]: 'POST',
+ [`${BASE}/access`]: 'GET, HEAD, POST',
+ [`${BASE}/access/tunnel`]: 'POST, DELETE',
}
const view: MachineView = {
@@ -54,11 +63,11 @@ interface HostFakes {
setEnabled: (enabled: boolean) => Promise<void>
profileViews: () => MachineView[]
discoveredViews: () => Promise<MachineView[]>
- status: (machineId: MachineId) => SshMachineStatus
- test: (machineId: MachineId, signal?: AbortSignal) => Promise<SshTestResult>
+ status: (machineId: MachineId) => RemoteMachineStatus
+ test: (machineId: MachineId, signal?: AbortSignal) => Promise<RemoteTestResult>
connect: (machineId: MachineId, signal?: AbortSignal) => Promise<{ machineId: MachineId, tunnelBaseUrl: string }>
disconnect: (machineId: MachineId) => Promise<void>
- install: (machineId: MachineId, signal?: AbortSignal) => Promise<SshInstallResponse>
+ install: (machineId: MachineId, signal?: AbortSignal) => Promise<RemoteInstallResponse>
events: (machineId: MachineId, sinceSeq?: number) => { events: unknown[], nextSeq: number }
save: (machineId: MachineId, row: Record<string, unknown>, secrets?: Record<string, unknown>) => Promise<void>
remove: (machineId: MachineId) => Promise<void>
@@ -80,7 +89,7 @@ function fakeHost(overrides: Partial<HostFakes> = {}): HostFakes {
profileViews: () => [view],
discoveredViews: async () => [],
status: () => ({ machineId: MachineId('m1'), state: 'disconnected' }),
- test: async (): Promise<SshTestResult> => ({ ok: true, banner: 'Linux alpha' }),
+ test: async (): Promise<RemoteTestResult> => ({ ok: true, banner: 'Linux alpha' }),
connect: async (machineId): Promise<{ machineId: MachineId, tunnelBaseUrl: string }> => ({ machineId, tunnelBaseUrl: 'http://127.0.0.1:45678' }),
disconnect: async () => {},
install: async () => ({ installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true }),
@@ -163,7 +172,13 @@ beforeAll(async () => {
closeServer = listener.close
})
+beforeEach(() => {
+ vi.stubEnv('DSH_REMOTE_SESSION_ORIGIN', undefined)
+})
+
afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllEnvs()
Object.assign(events, originalServices.events)
Object.assign(machine, originalServices.machine)
Object.assign(session, originalServices.session)
@@ -179,11 +194,13 @@ async function call<T = Record<string, unknown>>(
method: string,
path: string,
body?: unknown,
+ headers: Record<string, string> = {},
): Promise<{ status: number, body: T, allow: string | undefined }> {
const response = await fetch(`${origin}${path}`, {
method,
headers: {
connection: 'close',
+ ...headers,
...body === undefined ? {} : { 'content-type': 'application/json' },
},
...body === undefined ? {} : { body: JSON.stringify(body) },
@@ -237,14 +254,102 @@ describe('ssh REST route table', () => {
})
})
+describe('management request boundary', () => {
+ it('rejects every management read and mutation from nonlocal or untrusted sources before service calls', async () => {
+ installHost(fakeHost())
+ const services = [
+ ...Object.keys(machine).map(key => vi.spyOn(machine, key as keyof typeof machine)),
+ vi.spyOn(events, 'since'),
+ vi.spyOn(sync, 'preview'),
+ vi.spyOn(sync, 'apply'),
+ vi.spyOn(access, 'status').mockRejectedValue(new Error('management handler must not run')),
+ vi.spyOn(access, 'apply').mockRejectedValue(new Error('management handler must not run')),
+ vi.spyOn(access, 'ensureAuth').mockRejectedValue(new Error('management handler must not run')),
+ vi.spyOn(tunnel, 'start').mockRejectedValue(new Error('management handler must not run')),
+ vi.spyOn(tunnel, 'stop').mockRejectedValue(new Error('management handler must not run')),
+ ]
+ const session = ensureSourceSession()
+ const sources: Record<string, string>[] = [
+ ...['private', 'public', 'tunnel'].map(source => ({ [GATEWAY_SOURCE_HEADER]: source, [GATEWAY_SESSION_HEADER]: session })),
+ { [GATEWAY_SOURCE_HEADER]: 'loopback', [GATEWAY_SESSION_HEADER]: 'forged' },
+ { [GATEWAY_SOURCE_HEADER]: 'loopback' },
+ { [GATEWAY_SESSION_HEADER]: session },
+ { [GATEWAY_SOURCE_HEADER]: 'loopback, loopback', [GATEWAY_SESSION_HEADER]: session },
+ { [GATEWAY_SOURCE_HEADER]: 'unknown', [GATEWAY_SESSION_HEADER]: session },
+ { [GATEWAY_SOURCE_HEADER]: 'public', [GATEWAY_SESSION_HEADER]: 'outbound' },
+ ]
+ for (const headers of sources) {
+ for (const path of PATHS.filter(path => path !== `${BASE}/session/role`)) {
+ for (const method of ALLOW[path].split(', ')) {
+ const reply = await call(method, path, undefined, headers)
+ expect(reply.status, `${method} ${path} ${JSON.stringify(headers)}`).toBe(403)
+ expect(reply.body, `${method} ${path}`).toEqual(method === 'HEAD' ? {} : { error: LOOPBACK_ONLY_ERROR })
+ }
+ }
+ }
+ for (const service of services)
+ expect(service).not.toHaveBeenCalled()
+ })
+
+ it('reports remote roles per request while keeping the role probe readable', async () => {
+ installHost(fakeHost())
+ for (const source of ['private', 'public', 'tunnel', 'loopback']) {
+ const headers = { [GATEWAY_SOURCE_HEADER]: source, [GATEWAY_SESSION_HEADER]: source === 'loopback' ? 'forged' : ensureSourceSession() }
+ const response = await call('GET', `${BASE}/session/role?query=allowed`, undefined, headers)
+ expect(response.status).toBe(200)
+ expect(response.body).toEqual({ role: 'remote', remote: true })
+ expect((await call('HEAD', `${BASE}/session/role`, undefined, headers)).status).toBe(200)
+ expect((await call('GET', `${BASE}/settings?path=/api/tauri/remote/session/role`, undefined, headers)).status).toBe(403)
+ }
+ })
+
+ it('rejects management in an SSH remote process even on an unmarked loopback request', async () => {
+ vi.stubEnv('DSH_REMOTE_SESSION_ORIGIN', 'ops')
+ const read = vi.spyOn(machine, 'enabled')
+ const response = await call('GET', `${BASE}/settings`)
+ expect(response.status).toBe(403)
+ expect(response.body).toEqual({ error: LOOPBACK_ONLY_ERROR })
+ expect(read).not.toHaveBeenCalled()
+ const role = await call('GET', `${BASE}/session/role`)
+ expect(role.body).toEqual({ role: 'remote', remote: true, origin: 'ops' })
+ })
+
+ it('keeps native authentication ahead of the readable role exception', async () => {
+ const routes: HostWebRoute[] = []
+ const requestRejection = vi.fn(() => 401)
+ const dispose = server({
+ webServer: {
+ register: (route: HostWebRoute) => {
+ routes.push(route)
+ return () => {}
+ },
+ },
+ connection: { requestRejection },
+ logger: { error: () => {} },
+ } as never)
+ registered.push(...routes)
+ const original = registered.splice(0, PATHS.length)
+ try {
+ const role = await call('GET', `${BASE}/session/role`, undefined, { [GATEWAY_SOURCE_HEADER]: 'public' })
+ expect(role.status).toBe(401)
+ expect(role.body).toEqual({ error: 'unauthorized' })
+ expect(requestRejection).toHaveBeenCalledOnce()
+ }
+ finally {
+ registered.splice(0, routes.length, ...original)
+ dispose()
+ }
+ })
+})
+
describe('ssh REST handlers', () => {
it('answers session.role from the host', async () => {
installHost(fakeHost())
- const plain = await call<SshSessionRoleResponse>('GET', `${BASE}/session/role`)
+ const plain = await call<RemoteSessionRoleResponse>('GET', `${BASE}/session/role`)
expect(plain.status).toBe(200)
expect(plain.body).toEqual({ role: 'local', remote: false })
installHost(fakeHost({ sessionRole: () => ({ remote: true, origin: 'ops' }) }))
- const remote = await call<SshSessionRoleResponse>('GET', `${BASE}/session/role`)
+ const remote = await call<RemoteSessionRoleResponse>('GET', `${BASE}/session/role`)
expect(remote.body).toEqual({ role: 'remote', remote: true, origin: 'ops' })
})
@@ -252,11 +357,11 @@ describe('ssh REST handlers', () => {
const setEnabled = vi.fn(async () => {})
const host = fakeHost({ enabled: () => false, setEnabled })
installHost(host)
- const read = await call<SshSettingsResponse>('GET', `${BASE}/settings`)
+ const read = await call<RemoteSettingsResponse>('GET', `${BASE}/settings`)
expect(read.status).toBe(200)
expect(read.body).toEqual({ enabled: false })
- const written = await call<SshSettingsResponse>('POST', `${BASE}/settings`, { enabled: true })
+ const written = await call<RemoteSettingsResponse>('POST', `${BASE}/settings`, { enabled: true })
expect(written.status).toBe(200)
expect(written.body).toEqual({ enabled: true })
expect(setEnabled).toHaveBeenCalledWith(true)
@@ -265,7 +370,7 @@ describe('ssh REST handlers', () => {
it('refuses a settings write without a boolean switch', async () => {
const setEnabled = vi.fn(async () => {})
installHost(fakeHost({ setEnabled }))
- const reply = await call<SshSettingsResponse>('POST', `${BASE}/settings`, {})
+ const reply = await call<RemoteSettingsResponse>('POST', `${BASE}/settings`, {})
expect(reply.status).toBe(400)
expect(reply.body).toEqual({ error: 'missing enabled' })
expect(setEnabled).not.toHaveBeenCalled()
@@ -283,7 +388,7 @@ describe('ssh REST handlers', () => {
it('serves no machines while the feature is off (keeps the flag visible)', async () => {
installHost(fakeHost({ enabled: () => false, profileViews: () => [view], discoveredViews: async () => [view] }))
- const reply = await call<SshMachinesResponse>('GET', `${BASE}/machines`)
+ const reply = await call<RemoteMachinesResponse>('GET', `${BASE}/machines`)
expect(reply.status).toBe(200)
expect(reply.body).toEqual({ enabled: false, items: [], discovered: [] })
})
@@ -292,7 +397,7 @@ describe('ssh REST handlers', () => {
installHost(fakeHost({
status: () => ({ machineId: MachineId('m1'), state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1', lastError: 'boom' }),
}))
- const reply = await call<SshMachinesResponse>('GET', `${BASE}/machines`)
+ const reply = await call<RemoteMachinesResponse>('GET', `${BASE}/machines`)
expect(reply.status).toBe(200)
expect(reply.body).toEqual({
enabled: true,
@@ -317,7 +422,7 @@ describe('ssh REST handlers', () => {
? { machineId: id, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:2' }
: { machineId: id, state: 'disconnected' },
}))
- const reply = await call<SshMachinesResponse>('GET', `${BASE}/machines`)
+ const reply = await call<RemoteMachinesResponse>('GET', `${BASE}/machines`)
expect(reply.status).toBe(200)
expect(reply.body).toEqual({
enabled: true,
@@ -341,7 +446,7 @@ describe('ssh REST handlers', () => {
installHost(fakeHost({
status: () => ({ machineId: MachineId('m1'), state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } }),
}))
- const reply = await call<SshMachinesResponse>('GET', `${BASE}/machines`)
+ const reply = await call<RemoteMachinesResponse>('GET', `${BASE}/machines`)
expect(reply.status).toBe(200)
expect(reply.body).toEqual({
enabled: true,
@@ -352,14 +457,14 @@ describe('ssh REST handlers', () => {
it('lists machines without link fields while disconnected', async () => {
installHost(fakeHost())
- const reply = await call<SshMachinesResponse>('GET', `${BASE}/machines`)
+ const reply = await call<RemoteMachinesResponse>('GET', `${BASE}/machines`)
expect(reply.status).toBe(200)
expect(reply.body).toEqual({ enabled: true, items: [{ ...view, state: 'disconnected' }], discovered: [] })
})
it('carries the dshMissing marker on list rows', async () => {
installHost(fakeHost({ status: () => ({ machineId: MachineId('m1'), state: 'disconnected', dshMissing: true }) }))
- const reply = await call<SshMachinesResponse>('GET', `${BASE}/machines`)
+ const reply = await call<RemoteMachinesResponse>('GET', `${BASE}/machines`)
expect(reply.body.items?.[0]).toMatchObject({ dshMissing: true })
})
@@ -367,7 +472,7 @@ describe('ssh REST handlers', () => {
const save = vi.fn(async () => {})
installHost(fakeHost({ save }))
const password = 'p'.repeat(2 * 1024 * 1024)
- const reply = await call<SshActionResponse>('POST', `${BASE}/machines`, {
+ const reply = await call<RemoteActionResponse>('POST', `${BASE}/machines`, {
machineId: 'm1',
row: { name: 'alpha', host: '10.0.0.1', user: 'root' },
secrets: { password },
@@ -383,14 +488,14 @@ describe('ssh REST handlers', () => {
it('tests a machine', async () => {
installHost(fakeHost())
- const reply = await call<SshTestResponse>('POST', `${BASE}/machines/test`, { machineId: 'm1' })
+ const reply = await call<RemoteTestResponse>('POST', `${BASE}/machines/test`, { machineId: 'm1' })
expect(reply.status).toBe(200)
expect(reply.body).toEqual({ ok: true, banner: 'Linux alpha' })
})
it('connects a machine and returns the tunnel URL', async () => {
installHost(fakeHost())
- const reply = await call<SshConnectResponse>('POST', `${BASE}/machines/connect`, { machineId: 'm1' })
+ const reply = await call<RemoteConnectResponse>('POST', `${BASE}/machines/connect`, { machineId: 'm1' })
expect(reply.status).toBe(200)
expect(reply.body).toEqual({ tunnelBaseUrl: 'http://127.0.0.1:45678' })
})
@@ -398,7 +503,7 @@ describe('ssh REST handlers', () => {
it('saves a machine with write-only secrets', async () => {
const save = vi.fn(async () => {})
installHost(fakeHost({ save }))
- const reply = await call<SshActionResponse>('POST', `${BASE}/machines`, {
+ const reply = await call<RemoteActionResponse>('POST', `${BASE}/machines`, {
machineId: 'm1',
row: {
name: 'alpha',
@@ -429,18 +534,18 @@ describe('ssh REST handlers', () => {
it('rejects malformed machine writes', async () => {
const save = vi.fn(async () => {})
installHost(fakeHost({ save }))
- const missingRow = await call<SshActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1' })
+ const missingRow = await call<RemoteActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1' })
expect(missingRow.status).toBe(400)
expect(missingRow.body).toEqual({ error: 'missing row' })
- const badName = await call<SshActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1', row: { name: '', host: 'x', user: 'u' } })
+ const badName = await call<RemoteActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1', row: { name: '', host: 'x', user: 'u' } })
expect(badName.body).toEqual({ error: 'invalid row: name' })
- const badHost = await call<SshActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1', row: { name: 'a', host: '', user: 'u' } })
+ const badHost = await call<RemoteActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1', row: { name: 'a', host: '', user: 'u' } })
expect(badHost.body).toEqual({ error: 'invalid row: host' })
- const badUser = await call<SshActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1', row: { name: 'a', host: 'x', user: 7 } })
+ const badUser = await call<RemoteActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1', row: { name: 'a', host: 'x', user: 7 } })
expect(badUser.body).toEqual({ error: 'invalid row: user' })
- const badSecrets = await call<SshActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1', row: { name: 'a', host: 'x', user: 'u' }, secrets: 'nope' })
+ const badSecrets = await call<RemoteActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1', row: { name: 'a', host: 'x', user: 'u' }, secrets: 'nope' })
expect(badSecrets.body).toEqual({ error: 'invalid secrets' })
- const noMachine = await call<SshActionResponse>('POST', `${BASE}/machines`, { row: { name: 'a', host: 'x', user: 'u' } })
+ const noMachine = await call<RemoteActionResponse>('POST', `${BASE}/machines`, { row: { name: 'a', host: 'x', user: 'u' } })
expect(noMachine.body).toEqual({ error: 'missing machineId' })
expect(save).not.toHaveBeenCalled()
})
@@ -487,7 +592,7 @@ describe('ssh REST handlers', () => {
it('removes a machine', async () => {
const remove = vi.fn(async () => {})
installHost(fakeHost({ remove }))
- const reply = await call<SshActionResponse>('DELETE', `${BASE}/machines`, { machineId: 'm1' })
+ const reply = await call<RemoteActionResponse>('DELETE', `${BASE}/machines`, { machineId: 'm1' })
expect(reply.status).toBe(200)
expect(reply.body).toEqual({})
expect(remove).toHaveBeenCalledWith(MachineId('m1'))
@@ -496,7 +601,7 @@ describe('ssh REST handlers', () => {
it('requires a machineId on removal', async () => {
const remove = vi.fn(async () => {})
installHost(fakeHost({ remove }))
- const reply = await call<SshActionResponse>('DELETE', `${BASE}/machines`, {})
+ const reply = await call<RemoteActionResponse>('DELETE', `${BASE}/machines`, {})
expect(reply.status).toBe(400)
expect(reply.body).toEqual({ error: 'missing machineId' })
expect(remove).not.toHaveBeenCalled()
@@ -505,7 +610,7 @@ describe('ssh REST handlers', () => {
it('disconnects a machine', async () => {
const disconnect = vi.fn(async () => {})
installHost(fakeHost({ disconnect }))
- const reply = await call<SshActionResponse>('POST', `${BASE}/machines/disconnect`, { machineId: 'm1' })
+ const reply = await call<RemoteActionResponse>('POST', `${BASE}/machines/disconnect`, { machineId: 'm1' })
expect(reply.status).toBe(200)
expect(reply.body).toEqual({})
expect(disconnect).toHaveBeenCalledWith(MachineId('m1'))
@@ -514,7 +619,7 @@ describe('ssh REST handlers', () => {
it('installs dsh on a machine and returns the outcome', async () => {
const install = vi.fn(async () => ({ installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true }))
installHost(fakeHost({ install }))
- const reply = await call<SshInstallResponse>('POST', `${BASE}/machines/install`, { machineId: 'm1' })
+ const reply = await call<RemoteInstallResponse>('POST', `${BASE}/machines/install`, { machineId: 'm1' })
expect(reply.status).toBe(200)
expect(reply.body).toEqual({
installed: ['node'],
@@ -529,19 +634,19 @@ describe('ssh REST handlers', () => {
it('surfaces machine failures as 400 messages', async () => {
installHost(fakeHost({
install: async () => {
- throw new SshError('machine-install-failed', MachineId('m1'), 'pnpm: not found')
+ throw new RemoteError('machine-install-failed', MachineId('m1'), 'pnpm: not found')
},
}))
- const install = await call<SshInstallResponse>('POST', `${BASE}/machines/install`, { machineId: 'm1' })
+ const install = await call<RemoteInstallResponse>('POST', `${BASE}/machines/install`, { machineId: 'm1' })
expect(install.status).toBe(400)
expect(install.body).toEqual({ error: 'pnpm: not found' })
installHost(fakeHost({
test: async () => {
- throw new SshError('machine-connect-failed', MachineId('m1'), 'auth failed')
+ throw new RemoteError('machine-connect-failed', MachineId('m1'), 'auth failed')
},
}))
- const test = await call<SshTestResponse>('POST', `${BASE}/machines/test`, { machineId: 'm1' })
+ const test = await call<RemoteTestResponse>('POST', `${BASE}/machines/test`, { machineId: 'm1' })
expect(test.status).toBe(400)
expect(test.body).toEqual({ error: 'auth failed' })
@@ -550,7 +655,7 @@ describe('ssh REST handlers', () => {
throw new Error('tunnel broken')
},
}))
- const connect = await call<SshConnectResponse>('POST', `${BASE}/machines/connect`, { machineId: 'm1' })
+ const connect = await call<RemoteConnectResponse>('POST', `${BASE}/machines/connect`, { machineId: 'm1' })
expect(connect.status).toBe(400)
expect(connect.body).toEqual({ error: 'tunnel broken' })
})
@@ -562,14 +667,14 @@ describe('ssh REST handlers', () => {
throw 'boom'
},
}))
- const reply = await call<SshTestResponse>('POST', `${BASE}/machines/test`, { machineId: 'm1' })
+ const reply = await call<RemoteTestResponse>('POST', `${BASE}/machines/test`, { machineId: 'm1' })
expect(reply.status).toBe(400)
expect(reply.body).toEqual({ error: 'boom' })
})
it('requires a machineId on actions', async () => {
installHost(fakeHost())
- const reply = await call<SshTestResponse>('POST', `${BASE}/machines/test`, {})
+ const reply = await call<RemoteTestResponse>('POST', `${BASE}/machines/test`, {})
expect(reply.status).toBe(400)
expect(reply.body).toEqual({ error: 'missing machineId' })
})
@@ -634,7 +739,7 @@ describe('ssh REST handlers', () => {
it('drains machine events from the beginning', async () => {
installHost(fakeHost())
- const reply = await call<SshMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=m1`)
+ const reply = await call<RemoteMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=m1`)
expect(reply.status).toBe(200)
expect(reply.body).toEqual({
items: [
@@ -648,26 +753,26 @@ describe('ssh REST handlers', () => {
it('drains machine events incrementally by sinceSeq', async () => {
installHost(fakeHost())
- const reply = await call<SshMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=m1&sinceSeq=2`)
+ const reply = await call<RemoteMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=m1&sinceSeq=2`)
expect(reply.body).toMatchObject({ items: [expect.objectContaining({ seq: 3 })], nextSeq: 4 })
})
it('reports unknown event machines as an empty page anchored at seq 1', async () => {
installHost(fakeHost())
- const reply = await call<SshMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=ghost`)
+ const reply = await call<RemoteMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=ghost`)
expect(reply.body).toEqual({ items: [], nextSeq: 1 })
})
it('rejects malformed event cursors', async () => {
installHost(fakeHost())
- const negative = await call<SshMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=m1&sinceSeq=-1`)
+ const negative = await call<RemoteMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=m1&sinceSeq=-1`)
expect(negative.status).toBe(400)
expect(negative.body).toEqual({ error: 'invalid sinceSeq' })
- const fractional = await call<SshMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=m1&sinceSeq=1.5`)
+ const fractional = await call<RemoteMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=m1&sinceSeq=1.5`)
expect(fractional.body).toEqual({ error: 'invalid sinceSeq' })
- const missing = await call<SshMachineEventsResponse>('GET', `${BASE}/machines/events`)
+ const missing = await call<RemoteMachineEventsResponse>('GET', `${BASE}/machines/events`)
expect(missing.body).toEqual({ error: 'missing machineId' })
})
})
diff --git a/packages/dsh-tauri-remote/src/host/server/index.ts b/packages/dsh-tauri-remote/src/host/server/index.ts
new file mode 100644
index 00000000..304ca9d1
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/server/index.ts
@@ -0,0 +1,42 @@
+import { defineWebServer } from 'dsh-h3'
+import { guard } from 'dsh-tauri'
+import { remoteSourceGuard } from './panel.utils'
+import accessGet from './routes/access/get'
+import accessPost from './routes/access/post'
+import accessTunnelDelete from './routes/access/tunnel/delete'
+import accessTunnelPost from './routes/access/tunnel/post'
+import machinesConnect from './routes/machines/connect/post'
+import machinesDelete from './routes/machines/delete'
+import machinesDisconnect from './routes/machines/disconnect/post'
+import machinesEvents from './routes/machines/events/get'
+import machinesGet from './routes/machines/get'
+import machinesInstall from './routes/machines/install/post'
+import machinesPost from './routes/machines/post'
+import machinesTest from './routes/machines/test/post'
+import sessionRole from './routes/session/role/get'
+import settingsGet from './routes/settings/get'
+import settingsPost from './routes/settings/post'
+import syncApply from './routes/sync/apply/post'
+import syncPreview from './routes/sync/preview/get'
+
+export const server = defineWebServer((app) => {
+ app.use(guard)
+ app.use(remoteSourceGuard)
+ app.get('/api/tauri/remote/settings', settingsGet)
+ app.post('/api/tauri/remote/settings', settingsPost)
+ app.get('/api/tauri/remote/session/role', sessionRole)
+ app.get('/api/tauri/remote/machines', machinesGet)
+ app.post('/api/tauri/remote/machines', machinesPost)
+ app.delete('/api/tauri/remote/machines', machinesDelete)
+ app.post('/api/tauri/remote/machines/test', machinesTest)
+ app.post('/api/tauri/remote/machines/connect', machinesConnect)
+ app.post('/api/tauri/remote/machines/disconnect', machinesDisconnect)
+ app.post('/api/tauri/remote/machines/install', machinesInstall)
+ app.get('/api/tauri/remote/machines/events', machinesEvents)
+ app.get('/api/tauri/remote/sync/preview', syncPreview)
+ app.post('/api/tauri/remote/sync/apply', syncApply)
+ app.get('/api/tauri/remote/access', accessGet)
+ app.post('/api/tauri/remote/access', accessPost)
+ app.post('/api/tauri/remote/access/tunnel', accessTunnelPost)
+ app.delete('/api/tauri/remote/access/tunnel', accessTunnelDelete)
+})
diff --git a/packages/dsh-tauri-remote/src/host/server/panel.test.ts b/packages/dsh-tauri-remote/src/host/server/panel.test.ts
new file mode 100644
index 00000000..32a9bc6d
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/server/panel.test.ts
@@ -0,0 +1,191 @@
+import type { HostWebRoute } from '../types/index'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { createServer } from 'node:http'
+import { tmpdir } from 'node:os'
+import { join } from 'pathe'
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { GATEWAY_SESSION_HEADER, GATEWAY_SOURCE_HEADER } from '../config/constants'
+import { ensureSourceSession, setHostConfig } from '../config/runtime'
+import { access } from '../service/access'
+import { server } from './index'
+import { panel } from './panel'
+import { LOOPBACK_ONLY_ERROR } from './panel.utils'
+
+const BASE = '/api/tauri/remote'
+
+const PUBLIC_SOURCE = {
+ [GATEWAY_SOURCE_HEADER]: 'public',
+ 'x-forwarded-for': '203.0.113.7',
+}
+
+const registered: HostWebRoute[] = []
+let origin = ''
+let disposeRoutes: () => void
+let closeServer: () => Promise<void>
+let home = ''
+let previousHome: string | undefined
+
+function serveRoutes(): Promise<{ origin: string, close: () => Promise<void> }> {
+ const server = createServer((request, response) => {
+ const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname
+ const route = registered.find(entry => entry.path === path)
+ if (route === undefined) {
+ response.writeHead(404, { 'content-type': 'application/json' })
+ response.end('{"error":"no-route"}')
+ return
+ }
+ void route.handler(request, response)
+ })
+ return new Promise((resolve) => {
+ server.listen(0, '127.0.0.1', () => {
+ const address = server.address()
+ resolve({
+ origin: `http://127.0.0.1:${typeof address === 'object' && address !== null ? address.port : 0}`,
+ close: () => new Promise<void>(done => server.close(() => done())),
+ })
+ })
+ })
+}
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'dsh-remote-panel-'))
+ previousHome = process.env.DSH_HOME
+ process.env.DSH_HOME = home
+ setHostConfig({
+ connectTimeoutMs: 15_000,
+ healthCheckTimeoutMs: 1_000,
+ healthPollIntervalMs: 5,
+ healthPollAttempts: 3,
+ keepaliveIntervalMs: 10_000,
+ keepaliveCountMax: 3,
+ reconnectInitialDelayMs: 1,
+ reconnectMaxDelayMs: 2,
+ reconnectMaxAttempts: 2,
+ sshDir: join(home, 'ssh'),
+ })
+ const context = {
+ webServer: {
+ register: (route: HostWebRoute) => {
+ registered.push(route)
+ return () => {
+ registered.splice(registered.indexOf(route), 1)
+ }
+ },
+ },
+ logger: { error: () => {} },
+ } as never
+ const disposeServer = server(context)
+ const disposePanel = panel(context)
+ disposeRoutes = () => {
+ disposePanel()
+ disposeServer()
+ }
+ const listener = await serveRoutes()
+ origin = listener.origin
+ closeServer = listener.close
+})
+
+beforeEach(() => {
+ vi.stubEnv('DSH_REMOTE_SESSION_ORIGIN', undefined)
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllEnvs()
+})
+
+afterAll(async () => {
+ disposeRoutes()
+ await closeServer()
+ if (previousHome === undefined)
+ delete process.env.DSH_HOME
+ else
+ process.env.DSH_HOME = previousHome
+ rmSync(home, { recursive: true, force: true })
+})
+
+async function call(method: string, path: string, headers: Record<string, string> = {}, body?: unknown): Promise<{ status: number, body: Record<string, unknown>, allow: string | undefined }> {
+ const response = await fetch(`${origin}${path}`, {
+ method,
+ headers: {
+ connection: 'close',
+ ...headers,
+ ...body === undefined ? {} : { 'content-type': 'application/json' },
+ },
+ ...body === undefined ? {} : { body: JSON.stringify(body) },
+ })
+ const text = await response.text()
+ return {
+ status: response.status,
+ body: (text === '' ? {} : JSON.parse(text)) as Record<string, unknown>,
+ allow: response.headers.get('allow') ?? undefined,
+ }
+}
+
+describe('远端路由(真实注册 + HTTP)', () => {
+ it('只把入站分享与完整凭据管理挂到 /access 下', () => {
+ expect(registered.filter(route => route.path.startsWith(`${BASE}/access`)).map(route => `${route.kind} ${route.path}`)).toEqual([
+ `exact ${BASE}/access`,
+ `exact ${BASE}/access/tunnel`,
+ `exact ${BASE}/access/token`,
+ ])
+ })
+
+ it('声明每条面板路径的方法集', async () => {
+ expect((await call('OPTIONS', `${BASE}/access`)).allow).toBe('GET, POST, HEAD')
+ expect((await call('OPTIONS', `${BASE}/access/token`)).allow).toBe('POST, DELETE')
+ expect((await call('OPTIONS', `${BASE}/access/tunnel`)).allow).toBe('POST, DELETE')
+ })
+
+ it('回环来源可读完整状态', async () => {
+ const response = await call('GET', `${BASE}/access`)
+ expect(response.status).toBe(200)
+ expect(response.body).toHaveProperty('state')
+ })
+
+ it('非回环来源禁止读取状态且不进入凭据管理服务', async () => {
+ const status = vi.spyOn(access, 'status')
+ const response = await call('GET', `${BASE}/access`, PUBLIC_SOURCE)
+ expect(response.status).toBe(403)
+ expect(response.body).toEqual({ error: LOOPBACK_ONLY_ERROR })
+ expect(status).not.toHaveBeenCalled()
+ })
+
+ it('公网来源的写操作一律 403,且不进入 handler', async () => {
+ for (const [method, path] of [['POST', `${BASE}/access`], ['POST', `${BASE}/access/token`], ['DELETE', `${BASE}/access/token`], ['POST', `${BASE}/access/tunnel`], ['DELETE', `${BASE}/access/tunnel`]] as const) {
+ const response = await call(method, path, PUBLIC_SOURCE)
+ expect(response.status, `${method} ${path}`).toBe(403)
+ expect(response.body, `${method} ${path}`).toEqual({ error: LOOPBACK_ONLY_ERROR })
+ }
+ })
+
+ it('永久码管理拒绝可信远程、伪造回环与远程进程标记且不轮换凭据', async () => {
+ const rotate = vi.spyOn(access, 'rotate')
+ const revoke = vi.spyOn(access, 'revoke')
+ const sources: Record<string, string>[] = [
+ ...['private', 'public', 'tunnel'].map(source => ({ [GATEWAY_SOURCE_HEADER]: source, [GATEWAY_SESSION_HEADER]: ensureSourceSession() })),
+ { [GATEWAY_SOURCE_HEADER]: 'loopback', [GATEWAY_SESSION_HEADER]: 'forged' },
+ { [GATEWAY_SOURCE_HEADER]: 'loopback' },
+ { [GATEWAY_SESSION_HEADER]: ensureSourceSession() },
+ { [GATEWAY_SOURCE_HEADER]: 'public', [GATEWAY_SESSION_HEADER]: 'outbound' },
+ ]
+ for (const headers of sources) {
+ for (const method of ['POST', 'DELETE']) {
+ const response = await call(method, `${BASE}/access/token`, headers)
+ expect(response.status).toBe(403)
+ expect(response.body).toEqual({ error: LOOPBACK_ONLY_ERROR })
+ }
+ }
+ vi.stubEnv('DSH_REMOTE_SESSION_ORIGIN', 'ops')
+ expect((await call('POST', `${BASE}/access/token`)).status).toBe(403)
+ expect((await call('DELETE', `${BASE}/access/token`)).status).toBe(403)
+ expect(rotate).not.toHaveBeenCalled()
+ expect(revoke).not.toHaveBeenCalled()
+ })
+
+ it('回环来源的写操作进入 handler 并按 DTO 校验报 400', async () => {
+ const response = await call('POST', `${BASE}/access`, {}, { port: 'not-a-port' })
+ expect(response.status).toBe(400)
+ expect(response.body).toMatchObject({ error: expect.stringContaining('port') })
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/host/server/panel.ts b/packages/dsh-tauri-remote/src/host/server/panel.ts
new file mode 100644
index 00000000..e9af1d9e
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/server/panel.ts
@@ -0,0 +1,12 @@
+import { defineWebServer } from 'dsh-h3'
+import { guard } from 'dsh-tauri'
+import { remoteSourceGuard } from './panel.utils'
+import accessTokenDelete from './routes/access/token/delete'
+import accessTokenPost from './routes/access/token/post'
+
+export const panel = defineWebServer((app) => {
+ app.use(guard)
+ app.use(remoteSourceGuard)
+ app.post('/api/tauri/remote/access/token', accessTokenPost)
+ app.delete('/api/tauri/remote/access/token', accessTokenDelete)
+})
diff --git a/packages/dsh-tauri-remote/src/host/server/panel.utils.ts b/packages/dsh-tauri-remote/src/host/server/panel.utils.ts
new file mode 100644
index 00000000..d8cd6cfd
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/server/panel.utils.ts
@@ -0,0 +1,20 @@
+import type { Middleware } from 'h3'
+import type { IncomingMessage } from 'node:http'
+import { sourceSessionToken } from '../config/runtime'
+import { session } from '../service/session'
+import { isLoopbackSource } from '../utils/source'
+
+export const LOOPBACK_ONLY_ERROR = '管理接口仅限本机回环来源'
+
+export function isLocalRequest(event: { runtime?: unknown }): boolean {
+ const request = (event.runtime as { node?: { req?: IncomingMessage } } | undefined)?.node?.req
+ return request !== undefined && !session.role().remote
+ && isLoopbackSource(request.headers, request.socket?.remoteAddress, sourceSessionToken())
+}
+
+export const remoteSourceGuard: Middleware = async (event, next) => {
+ if (isLocalRequest(event) || ((event.req.method === 'GET' || event.req.method === 'HEAD') && event.url.pathname === '/api/tauri/remote/session/role'))
+ return next()
+ event.res.status = 403
+ return { error: LOOPBACK_ONLY_ERROR }
+}
diff --git a/packages/dsh-tauri-remote/src/host/server/routes/access/get.ts b/packages/dsh-tauri-remote/src/host/server/routes/access/get.ts
new file mode 100644
index 00000000..610216fd
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/server/routes/access/get.ts
@@ -0,0 +1,17 @@
+import type { EventHandlerRequest } from 'h3'
+import type { RemoteAccessStatus } from '../../../service/access.types'
+import type { GetAccessQuery } from '../index.types'
+import { defineEventHandler, getQuery, HTTPError } from 'h3'
+import { access } from '../../../service/access'
+import { waitForPairingUse } from '../../../service/pairing'
+
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteAccessStatus>>(async (event) => {
+ const query = getQuery<GetAccessQuery>(event)
+ const raw = query.sincePairingUseSeq
+ const since = raw === undefined ? undefined : typeof raw === 'string' && /^\d+$/u.test(raw) ? Number(raw) : Number.NaN
+ if (since !== undefined && (!Number.isSafeInteger(since) || since < 0))
+ throw new HTTPError({ statusCode: 400, message: 'invalid sincePairingUseSeq' })
+ if (since !== undefined)
+ await waitForPairingUse(since, event.req.signal)
+ return await access.status()
+})
diff --git a/packages/dsh-tauri-remote/src/host/server/routes/access/post.ts b/packages/dsh-tauri-remote/src/host/server/routes/access/post.ts
new file mode 100644
index 00000000..824e2744
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/server/routes/access/post.ts
@@ -0,0 +1,10 @@
+import type { EventHandlerRequest } from 'h3'
+import type { RemoteAccessBody, RemoteAccessStatus } from '../../../service/access.types'
+import { defineEventHandler, readBody } from 'h3'
+import { access } from '../../../service/access'
+import { guarded } from '../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteAccessStatus | { error: string }>>(async (event) => {
+ const body = (await readBody<RemoteAccessBody>(event)) ?? {}
+ return await guarded(event, async () => await access.apply(body))
+})
diff --git a/packages/dsh-tauri-remote/src/host/server/routes/access/token/delete.ts b/packages/dsh-tauri-remote/src/host/server/routes/access/token/delete.ts
new file mode 100644
index 00000000..a352f551
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/server/routes/access/token/delete.ts
@@ -0,0 +1,8 @@
+import type { EventHandlerRequest } from 'h3'
+import type { RemoteAccessStatus } from '../../../../service/access.types'
+import { defineEventHandler } from 'h3'
+import { access } from '../../../../service/access'
+import { guarded } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteAccessStatus | { error: string }>>(async event =>
+ guarded(event, async () => await access.revoke()))
diff --git a/packages/dsh-tauri-remote/src/host/server/routes/access/token/post.ts b/packages/dsh-tauri-remote/src/host/server/routes/access/token/post.ts
new file mode 100644
index 00000000..74441e8e
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/server/routes/access/token/post.ts
@@ -0,0 +1,8 @@
+import type { EventHandlerRequest } from 'h3'
+import type { RemoteAccessStatus } from '../../../../service/access.types'
+import { defineEventHandler } from 'h3'
+import { access } from '../../../../service/access'
+import { guarded } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteAccessStatus | { error: string }>>(async event =>
+ guarded(event, async () => await access.rotate()))
diff --git a/packages/dsh-tauri-remote/src/host/server/routes/access/tunnel/delete.ts b/packages/dsh-tauri-remote/src/host/server/routes/access/tunnel/delete.ts
new file mode 100644
index 00000000..7485dbbf
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/server/routes/access/tunnel/delete.ts
@@ -0,0 +1,13 @@
+import type { EventHandlerRequest } from 'h3'
+import type { RemoteAccessStatus } from '../../../../service/access.types'
+import { defineEventHandler } from 'h3'
+import { access } from '../../../../service/access'
+import { tunnel } from '../../../../service/tunnel'
+import { guarded } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteAccessStatus | { error: string }>>(async (event) => {
+ return await guarded(event, async () => {
+ await tunnel.stop()
+ return await access.status()
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/host/server/routes/access/tunnel/post.ts b/packages/dsh-tauri-remote/src/host/server/routes/access/tunnel/post.ts
new file mode 100644
index 00000000..187ff89f
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/server/routes/access/tunnel/post.ts
@@ -0,0 +1,36 @@
+import type { EventHandlerRequest } from 'h3'
+import type { RemoteAccessStatus } from '../../../../service/access.types'
+import type { RemoteTunnelMode } from '../../../../types/index'
+import type { RemoteAccessTunnelBody } from '../../index.types'
+import { defineEventHandler, readBody } from 'h3'
+import { access } from '../../../../service/access'
+import { tunnel } from '../../../../service/tunnel'
+import { guarded } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteAccessStatus | { error: string }>>(async (event) => {
+ const body = (await readBody<RemoteAccessTunnelBody>(event)) ?? {}
+ return await guarded(event, async () => {
+ const mode = modeOf(body.mode)
+ const credential = textOf(body.token, 'token')
+ const host = textOf(body.hostname, 'hostname')
+ tunnel.assertStartable(mode, credential, host)
+ const ensured = await access.ensureAuth()
+ await tunnel.start(mode, credential, host)
+ const status = await access.status()
+ return ensured.generatedPassword === undefined ? status : { ...status, generatedPassword: ensured.generatedPassword }
+ })
+})
+
+function modeOf(value: unknown): RemoteTunnelMode {
+ if (value === 'quick' || value === 'token')
+ return value
+ throw new Error('invalid mode: quick | token')
+}
+
+function textOf(value: unknown, field: string): string | undefined {
+ if (value === undefined || value === null)
+ return undefined
+ if (typeof value !== 'string')
+ throw new Error(`invalid ${field}`)
+ return value
+}
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/index.types.ts b/packages/dsh-tauri-remote/src/host/server/routes/index.types.ts
similarity index 63%
rename from packages/dsh-tauri-ssh/src/host/server/routes/index.types.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/index.types.ts
index 7f5967b8..da499526 100644
--- a/packages/dsh-tauri-ssh/src/host/server/routes/index.types.ts
+++ b/packages/dsh-tauri-remote/src/host/server/routes/index.types.ts
@@ -1,6 +1,6 @@
-import type { SshAuthMethod, SshConnectionState, SshProgress } from '../../types/index'
+import type { RemoteAuthMethod, RemoteConnectionState, RemoteProgress, RemoteTunnelMode } from '../../types/index'
-export interface SshMachineListItem {
+export interface RemoteMachineListItem {
id?: string
name?: string
host?: string
@@ -13,39 +13,39 @@ export interface SshMachineListItem {
startCommand?: string
color?: string
tintBorder?: boolean
- state?: SshConnectionState
+ state?: RemoteConnectionState
tunnelBaseUrl?: string
lastError?: string
dshMissing?: boolean
- progress?: SshProgress
+ progress?: RemoteProgress
nextRetryAt?: number
- authMethod?: SshAuthMethod
+ authMethod?: RemoteAuthMethod
}
-export interface SshSettingsBody {
+export interface RemoteSettingsBody {
enabled?: boolean
}
-export interface SshSettingsResponse {
+export interface RemoteSettingsResponse {
enabled?: boolean
error?: string
}
-export interface SshSessionRoleResponse {
+export interface RemoteSessionRoleResponse {
role?: string
remote?: boolean
origin?: string
error?: string
}
-export interface SshMachinesResponse {
+export interface RemoteMachinesResponse {
enabled?: boolean
- items?: SshMachineListItem[]
- discovered?: SshMachineListItem[]
+ items?: RemoteMachineListItem[]
+ discovered?: RemoteMachineListItem[]
error?: string
}
-export interface SshMachineRowBody {
+export interface RemoteMachineRowBody {
name?: string
host?: string
port?: number
@@ -57,27 +57,37 @@ export interface SshMachineRowBody {
tintBorder?: boolean
}
-export interface SshMachineSecretsBody {
+export interface RemoteMachineSecretsBody {
password?: string
passphrase?: string
}
-export interface SshMachineSaveBody {
+export interface RemoteMachineSaveBody {
machineId?: string
- row?: SshMachineRowBody
- secrets?: SshMachineSecretsBody
+ row?: RemoteMachineRowBody
+ secrets?: RemoteMachineSecretsBody
}
-export interface SshMachineIdBody {
+export interface RemoteMachineIdBody {
machineId?: string
}
-export interface SshMachineEventsQuery {
+export interface RemoteAccessTunnelBody {
+ mode?: RemoteTunnelMode
+ token?: string
+ hostname?: string
+}
+
+export interface GetAccessQuery {
+ sincePairingUseSeq?: number
+}
+
+export interface GetMachinesEventsQuery {
machineId?: string
sinceSeq?: number
}
-export interface SshMachineEventItem {
+export interface RemoteMachineEventItem {
seq?: number
ts?: string
machineId?: string
@@ -87,25 +97,25 @@ export interface SshMachineEventItem {
reason?: string
}
-export interface SshMachineEventsResponse {
- items?: SshMachineEventItem[]
+export interface RemoteMachineEventsResponse {
+ items?: RemoteMachineEventItem[]
nextSeq?: number
error?: string
}
-export interface SshTestResponse {
+export interface RemoteTestResponse {
ok?: boolean
banner?: string
message?: string
error?: string
}
-export interface SshConnectResponse {
+export interface RemoteConnectResponse {
tunnelBaseUrl?: string
error?: string
}
-export interface SshInstallResponse {
+export interface RemoteInstallResponse {
installed?: string[]
dshRef?: string
dshVersion?: string
@@ -115,7 +125,7 @@ export interface SshInstallResponse {
error?: string
}
-export interface SshActionResponse {
+export interface RemoteActionResponse {
error?: string
}
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/index.utils.ts b/packages/dsh-tauri-remote/src/host/server/routes/index.utils.ts
similarity index 94%
rename from packages/dsh-tauri-ssh/src/host/server/routes/index.utils.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/index.utils.ts
index f1d86258..ccf014be 100644
--- a/packages/dsh-tauri-ssh/src/host/server/routes/index.utils.ts
+++ b/packages/dsh-tauri-remote/src/host/server/routes/index.utils.ts
@@ -1,5 +1,5 @@
-import type { MachineSaveRow, MachineSecretWrite, MachineView, SshMachineStatus, SyncPluginRef, SyncSkillRef, SyncSkillRoot } from '../../types/index'
-import type { SshMachineListItem } from './index.types'
+import type { MachineSaveRow, MachineSecretWrite, MachineView, RemoteMachineStatus, SyncPluginRef, SyncSkillRef, SyncSkillRoot } from '../../types/index'
+import type { RemoteMachineListItem } from './index.types'
import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../../shared/constants'
import { MachineId } from '../../types/index'
@@ -16,7 +16,7 @@ export async function guarded<T>(event: { res: { status?: number } }, run: () =>
}
}
-export function listItemOf(view: MachineView, status: SshMachineStatus): SshMachineListItem {
+export function listItemOf(view: MachineView, status: RemoteMachineStatus): RemoteMachineListItem {
return {
...view,
state: status.state,
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/machines/connect/post.ts b/packages/dsh-tauri-remote/src/host/server/routes/machines/connect/post.ts
similarity index 60%
rename from packages/dsh-tauri-ssh/src/host/server/routes/machines/connect/post.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/machines/connect/post.ts
index e97eaa25..aab324ff 100644
--- a/packages/dsh-tauri-ssh/src/host/server/routes/machines/connect/post.ts
+++ b/packages/dsh-tauri-remote/src/host/server/routes/machines/connect/post.ts
@@ -1,11 +1,11 @@
import type { EventHandlerRequest } from 'h3'
-import type { SshConnectResponse, SshMachineIdBody } from '../../index.types'
+import type { RemoteConnectResponse, RemoteMachineIdBody } from '../../index.types'
import { defineEventHandler, readBody } from 'h3'
import { machine } from '../../../../service/machine'
import { guarded, machineIdOf } from '../../index.utils'
-export default defineEventHandler<EventHandlerRequest, Promise<SshConnectResponse>>(async (event) => {
- const body = (await readBody<SshMachineIdBody>(event)) ?? {}
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteConnectResponse>>(async (event) => {
+ const body = (await readBody<RemoteMachineIdBody>(event)) ?? {}
return guarded(event, async () => {
const link = await machine.connect(machineIdOf(body), new AbortController().signal)
return { tunnelBaseUrl: link.tunnelBaseUrl }
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/machines/delete.ts b/packages/dsh-tauri-remote/src/host/server/routes/machines/delete.ts
similarity index 54%
rename from packages/dsh-tauri-ssh/src/host/server/routes/machines/delete.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/machines/delete.ts
index 5049e977..1f1d1b81 100644
--- a/packages/dsh-tauri-ssh/src/host/server/routes/machines/delete.ts
+++ b/packages/dsh-tauri-remote/src/host/server/routes/machines/delete.ts
@@ -1,11 +1,11 @@
import type { EventHandlerRequest } from 'h3'
-import type { SshActionResponse, SshMachineIdBody } from '../index.types'
+import type { RemoteActionResponse, RemoteMachineIdBody } from '../index.types'
import { defineEventHandler, readBody } from 'h3'
import { machine } from '../../../service/machine'
import { guarded, machineIdOf } from '../index.utils'
-export default defineEventHandler<EventHandlerRequest, Promise<SshActionResponse>>(async (event) => {
- const body = (await readBody<SshMachineIdBody>(event)) ?? {}
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteActionResponse>>(async (event) => {
+ const body = (await readBody<RemoteMachineIdBody>(event)) ?? {}
return guarded(event, async () => {
await machine.remove(machineIdOf(body))
return {}
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/machines/disconnect/post.ts b/packages/dsh-tauri-remote/src/host/server/routes/machines/disconnect/post.ts
similarity index 55%
rename from packages/dsh-tauri-ssh/src/host/server/routes/machines/disconnect/post.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/machines/disconnect/post.ts
index f62d511f..b80c62d2 100644
--- a/packages/dsh-tauri-ssh/src/host/server/routes/machines/disconnect/post.ts
+++ b/packages/dsh-tauri-remote/src/host/server/routes/machines/disconnect/post.ts
@@ -1,11 +1,11 @@
import type { EventHandlerRequest } from 'h3'
-import type { SshActionResponse, SshMachineIdBody } from '../../index.types'
+import type { RemoteActionResponse, RemoteMachineIdBody } from '../../index.types'
import { defineEventHandler, readBody } from 'h3'
import { machine } from '../../../../service/machine'
import { guarded, machineIdOf } from '../../index.utils'
-export default defineEventHandler<EventHandlerRequest, Promise<SshActionResponse>>(async (event) => {
- const body = (await readBody<SshMachineIdBody>(event)) ?? {}
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteActionResponse>>(async (event) => {
+ const body = (await readBody<RemoteMachineIdBody>(event)) ?? {}
return guarded(event, async () => {
await machine.disconnect(machineIdOf(body))
return {}
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/machines/events/get.ts b/packages/dsh-tauri-remote/src/host/server/routes/machines/events/get.ts
similarity index 59%
rename from packages/dsh-tauri-ssh/src/host/server/routes/machines/events/get.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/machines/events/get.ts
index 4076fff6..3f3f8b50 100644
--- a/packages/dsh-tauri-ssh/src/host/server/routes/machines/events/get.ts
+++ b/packages/dsh-tauri-remote/src/host/server/routes/machines/events/get.ts
@@ -1,11 +1,11 @@
import type { EventHandlerRequest } from 'h3'
-import type { SshMachineEventsQuery, SshMachineEventsResponse } from '../../index.types'
+import type { GetMachinesEventsQuery, RemoteMachineEventsResponse } from '../../index.types'
import { defineEventHandler, getQuery } from 'h3'
import { events } from '../../../../service/events'
import { guarded, machineIdOf, sinceSeqOf } from '../../index.utils'
-export default defineEventHandler<EventHandlerRequest, Promise<SshMachineEventsResponse>>(async (event) => {
- const query = getQuery<SshMachineEventsQuery>(event)
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteMachineEventsResponse>>(async (event) => {
+ const query = getQuery<GetMachinesEventsQuery>(event)
return guarded(event, async () => {
const page = events.since(machineIdOf(query), sinceSeqOf(query))
return { items: page.events, nextSeq: page.nextSeq }
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/machines/get.ts b/packages/dsh-tauri-remote/src/host/server/routes/machines/get.ts
similarity index 77%
rename from packages/dsh-tauri-ssh/src/host/server/routes/machines/get.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/machines/get.ts
index a2375fb5..1c8b2867 100644
--- a/packages/dsh-tauri-ssh/src/host/server/routes/machines/get.ts
+++ b/packages/dsh-tauri-remote/src/host/server/routes/machines/get.ts
@@ -1,10 +1,10 @@
import type { EventHandlerRequest } from 'h3'
-import type { SshMachinesResponse } from '../index.types'
+import type { RemoteMachinesResponse } from '../index.types'
import { defineEventHandler } from 'h3'
import { machine } from '../../../service/machine'
import { guarded, listItemOf } from '../index.utils'
-export default defineEventHandler<EventHandlerRequest, Promise<SshMachinesResponse>>(async event =>
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteMachinesResponse>>(async event =>
guarded(event, async () => {
if (!machine.enabled())
return { enabled: false, items: [], discovered: [] }
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/machines/install/post.ts b/packages/dsh-tauri-remote/src/host/server/routes/machines/install/post.ts
similarity index 56%
rename from packages/dsh-tauri-ssh/src/host/server/routes/machines/install/post.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/machines/install/post.ts
index 5fa152ee..af39cb99 100644
--- a/packages/dsh-tauri-ssh/src/host/server/routes/machines/install/post.ts
+++ b/packages/dsh-tauri-remote/src/host/server/routes/machines/install/post.ts
@@ -1,11 +1,11 @@
import type { EventHandlerRequest } from 'h3'
-import type { SshInstallResponse, SshMachineIdBody } from '../../index.types'
+import type { RemoteInstallResponse, RemoteMachineIdBody } from '../../index.types'
import { defineEventHandler, readBody } from 'h3'
import { machine } from '../../../../service/machine'
import { guarded, machineIdOf } from '../../index.utils'
-export default defineEventHandler<EventHandlerRequest, Promise<SshInstallResponse>>(async (event) => {
- const body = (await readBody<SshMachineIdBody>(event)) ?? {}
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteInstallResponse>>(async (event) => {
+ const body = (await readBody<RemoteMachineIdBody>(event)) ?? {}
return guarded(event, async () => {
return await machine.install(machineIdOf(body), new AbortController().signal)
})
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/machines/post.ts b/packages/dsh-tauri-remote/src/host/server/routes/machines/post.ts
similarity index 58%
rename from packages/dsh-tauri-ssh/src/host/server/routes/machines/post.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/machines/post.ts
index a8748363..25cc2a48 100644
--- a/packages/dsh-tauri-ssh/src/host/server/routes/machines/post.ts
+++ b/packages/dsh-tauri-remote/src/host/server/routes/machines/post.ts
@@ -1,11 +1,11 @@
import type { EventHandlerRequest } from 'h3'
-import type { SshActionResponse, SshMachineSaveBody } from '../index.types'
+import type { RemoteActionResponse, RemoteMachineSaveBody } from '../index.types'
import { defineEventHandler, readBody } from 'h3'
import { machine } from '../../../service/machine'
import { guarded, machineIdOf, saveRowOf, secretsOf } from '../index.utils'
-export default defineEventHandler<EventHandlerRequest, Promise<SshActionResponse>>(async (event) => {
- const body = (await readBody<SshMachineSaveBody>(event)) ?? {}
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteActionResponse>>(async (event) => {
+ const body = (await readBody<RemoteMachineSaveBody>(event)) ?? {}
return guarded(event, async () => {
await machine.save(machineIdOf(body), saveRowOf(body), secretsOf(body))
return {}
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/machines/test/post.ts b/packages/dsh-tauri-remote/src/host/server/routes/machines/test/post.ts
similarity index 57%
rename from packages/dsh-tauri-ssh/src/host/server/routes/machines/test/post.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/machines/test/post.ts
index d967bdcd..57db535c 100644
--- a/packages/dsh-tauri-ssh/src/host/server/routes/machines/test/post.ts
+++ b/packages/dsh-tauri-remote/src/host/server/routes/machines/test/post.ts
@@ -1,11 +1,11 @@
import type { EventHandlerRequest } from 'h3'
-import type { SshMachineIdBody, SshTestResponse } from '../../index.types'
+import type { RemoteMachineIdBody, RemoteTestResponse } from '../../index.types'
import { defineEventHandler, readBody } from 'h3'
import { machine } from '../../../../service/machine'
import { guarded, machineIdOf } from '../../index.utils'
-export default defineEventHandler<EventHandlerRequest, Promise<SshTestResponse>>(async (event) => {
- const body = (await readBody<SshMachineIdBody>(event)) ?? {}
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteTestResponse>>(async (event) => {
+ const body = (await readBody<RemoteMachineIdBody>(event)) ?? {}
return guarded(event, async () => {
return await machine.test(machineIdOf(body), new AbortController().signal)
})
diff --git a/packages/dsh-tauri-remote/src/host/server/routes/session/role/get.ts b/packages/dsh-tauri-remote/src/host/server/routes/session/role/get.ts
new file mode 100644
index 00000000..1ce75c1e
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/server/routes/session/role/get.ts
@@ -0,0 +1,13 @@
+import type { EventHandlerRequest } from 'h3'
+import type { RemoteSessionRoleResponse } from '../../index.types'
+import { defineEventHandler } from 'h3'
+import { session } from '../../../../service/session'
+import { isLocalRequest } from '../../../panel.utils'
+import { guarded } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteSessionRoleResponse>>(async event =>
+ guarded(event, async () => {
+ const role = session.role()
+ const remote = !isLocalRequest(event)
+ return { ...role, remote, role: remote ? 'remote' : 'local' }
+ }))
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/settings/get.ts b/packages/dsh-tauri-remote/src/host/server/routes/settings/get.ts
similarity index 59%
rename from packages/dsh-tauri-ssh/src/host/server/routes/settings/get.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/settings/get.ts
index c28c53ee..9c5f4d3d 100644
--- a/packages/dsh-tauri-ssh/src/host/server/routes/settings/get.ts
+++ b/packages/dsh-tauri-remote/src/host/server/routes/settings/get.ts
@@ -1,8 +1,8 @@
import type { EventHandlerRequest } from 'h3'
-import type { SshSettingsResponse } from '../index.types'
+import type { RemoteSettingsResponse } from '../index.types'
import { defineEventHandler } from 'h3'
import { machine } from '../../../service/machine'
import { guarded } from '../index.utils'
-export default defineEventHandler<EventHandlerRequest, Promise<SshSettingsResponse>>(async event =>
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteSettingsResponse>>(async event =>
guarded(event, async () => ({ enabled: machine.enabled() })))
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/settings/post.ts b/packages/dsh-tauri-remote/src/host/server/routes/settings/post.ts
similarity index 57%
rename from packages/dsh-tauri-ssh/src/host/server/routes/settings/post.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/settings/post.ts
index 2c44348d..c623bae1 100644
--- a/packages/dsh-tauri-ssh/src/host/server/routes/settings/post.ts
+++ b/packages/dsh-tauri-remote/src/host/server/routes/settings/post.ts
@@ -1,11 +1,11 @@
import type { EventHandlerRequest } from 'h3'
-import type { SshSettingsBody, SshSettingsResponse } from '../index.types'
+import type { RemoteSettingsBody, RemoteSettingsResponse } from '../index.types'
import { defineEventHandler, readBody } from 'h3'
import { machine } from '../../../service/machine'
import { enabledOf, guarded } from '../index.utils'
-export default defineEventHandler<EventHandlerRequest, Promise<SshSettingsResponse>>(async (event) => {
- const body = (await readBody<SshSettingsBody>(event)) ?? {}
+export default defineEventHandler<EventHandlerRequest, Promise<RemoteSettingsResponse>>(async (event) => {
+ const body = (await readBody<RemoteSettingsBody>(event)) ?? {}
return guarded(event, async () => {
const enabled = enabledOf(body)
await machine.setEnabled(enabled)
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/sync/apply/post.ts b/packages/dsh-tauri-remote/src/host/server/routes/sync/apply/post.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/server/routes/sync/apply/post.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/sync/apply/post.ts
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/sync/preview/get.ts b/packages/dsh-tauri-remote/src/host/server/routes/sync/preview/get.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/server/routes/sync/preview/get.ts
rename to packages/dsh-tauri-remote/src/host/server/routes/sync/preview/get.ts
diff --git a/packages/dsh-tauri-remote/src/host/service/access.test.ts b/packages/dsh-tauri-remote/src/host/service/access.test.ts
new file mode 100644
index 00000000..86a71739
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/access.test.ts
@@ -0,0 +1,639 @@
+import type { IncomingHttpHeaders } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import type { HostWebRoute, RemoteHostContext } from '../types/index'
+import type { RemoteAccessDocument, RemoteAccessStatus } from './access.types'
+import { Buffer } from 'node:buffer'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { createServer, request as httpRequest } from 'node:http'
+import { networkInterfaces, tmpdir } from 'node:os'
+import { dirname, join } from 'pathe'
+import { toDataURL } from 'qrcode'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { ensureSourceSession, setCurrentHostInstance } from '../config/runtime'
+import { server as remoteServer } from '../server'
+import { verifyPassword } from '../utils/auth'
+import { access } from './access'
+import { defaultAccessDocument, enumerateAddresses, isReachableAddress, readAccessDocument, writeAccessDocument } from './access.utils'
+import { gateway } from './gateway'
+import { consumePairingCode, pairingCodeOf, resetPairingCode } from './pairing'
+
+const homes: string[] = []
+
+let previousHome: string | undefined
+
+let previousPort: string | undefined
+
+let upstream: Upstream
+
+let mintAuthorities: string[]
+
+interface Reply {
+ status: number
+ body: string
+ headers: IncomingHttpHeaders
+}
+
+interface Upstream {
+ port: number
+ calls: Array<{ url: string, cookie: string | undefined }>
+ close: () => Promise<void>
+}
+
+/** 最小 DSH 等价上游:`/?token=` 铸造 authority 绑定 cookie,其余请求记录并回 200。 */
+function startUpstream(): Promise<Upstream> {
+ const calls: Upstream['calls'] = []
+ const registered: HostWebRoute[] = []
+ const disposeRoutes = remoteServer({
+ webServer: { register: (route: HostWebRoute) => {
+ registered.push(route)
+ return () => {}
+ } },
+ logger: { error: () => {} },
+ } as never)
+ const server = createServer((request, response) => {
+ const route = registered.find(entry => entry.path === new URL(request.url ?? '/', 'http://127.0.0.1').pathname)
+ if (route !== undefined) {
+ void route.handler(request, response)
+ return
+ }
+ calls.push({ url: request.url ?? '', cookie: request.headers.cookie })
+ if (request.url?.startsWith('/?token=')) {
+ response.writeHead(303, { 'set-cookie': 'dsh-auth-probe=granted; Path=/', 'location': '/' })
+ response.end()
+ return
+ }
+ response.writeHead(200, { 'content-type': request.url === '/' ? 'text/html' : 'application/json' })
+ response.end(request.url === '/' ? '<html>dsh</html>' : '{"ok":true}')
+ })
+ return new Promise((resolve) => {
+ server.listen(0, '127.0.0.1', () => {
+ const address = server.address() as AddressInfo
+ resolve({
+ port: address.port,
+ calls,
+ close: () => new Promise<void>((done) => {
+ disposeRoutes()
+ server.close(() => done())
+ }),
+ })
+ })
+ })
+}
+
+function call(port: number, path: string, options: { source?: string, cookie?: string, method?: string, form?: string } = {}): Promise<Reply> {
+ return new Promise((resolve, reject) => {
+ const request = httpRequest({
+ host: '127.0.0.1',
+ port,
+ path,
+ method: options.method ?? 'GET',
+ headers: {
+ connection: 'close',
+ ...options.source === undefined ? {} : { 'x-dsh-remote-source': options.source, 'x-dsh-remote-session': ensureSourceSession() },
+ ...options.cookie === undefined ? {} : { cookie: options.cookie },
+ ...options.form === undefined ? {} : { 'accept': 'text/html', 'content-type': 'application/x-www-form-urlencoded' },
+ },
+ }, (response) => {
+ const chunks: Buffer[] = []
+ response.on('data', (chunk: Buffer) => chunks.push(chunk))
+ response.on('end', () => resolve({ status: response.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8'), headers: response.headers }))
+ })
+ request.on('error', reject)
+ request.end(options.form)
+ })
+}
+
+function signIn(port: number, password: string): Promise<Reply> {
+ return call(port, '/', { source: 'public', method: 'POST', form: `password=${encodeURIComponent(password)}` })
+}
+
+function freePort(): Promise<number> {
+ const server = createServer()
+ return new Promise((resolve) => {
+ server.listen(0, '127.0.0.1', () => {
+ const address = server.address() as AddressInfo
+ server.close(() => resolve(address.port))
+ })
+ })
+}
+
+function occupy(host: string, port: number): Promise<() => Promise<void>> {
+ const server = createServer()
+ return new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(port, host, () => resolve(() => new Promise<void>(done => server.close(() => done()))))
+ })
+}
+
+/** 与 gateway.ts 的端口回落上限对齐:真实候选端口 = 首选 + 该上限。 */
+const PORT_FALLBACK_LIMIT = 20
+
+async function occupyRange(size: number): Promise<{ base: number, release: () => Promise<void> }> {
+ for (let base = 20_000; base + size < 60_000; base += 256) {
+ const releases: Array<() => Promise<void>> = []
+ for (let offset = 0; offset < size; offset++) {
+ try {
+ releases.push(await occupy('127.0.0.1', base + offset))
+ }
+ catch {
+ break
+ }
+ }
+ if (releases.length === size) {
+ return {
+ base,
+ release: async () => {
+ for (const release of releases.reverse())
+ await release()
+ },
+ }
+ }
+ for (const release of releases.reverse())
+ await release()
+ }
+ throw new Error('测试断言失败:本机找不到连续空闲端口段')
+}
+
+function sessionCookieOf(headers: IncomingHttpHeaders): string {
+ const values = headers['set-cookie'] ?? []
+ const pair = values.map(value => value.split(';')[0] ?? '').find(value => value.startsWith('dsh_remote_session='))
+ if (pair === undefined)
+ throw new Error('测试断言失败:登录响应没有下发 dsh_remote_session')
+ return pair
+}
+
+function tokenOf(link: string | undefined): string {
+ const token = link === undefined ? null : new URL(link).searchParams.get('auth')
+ if (token === null || token === '')
+ throw new Error('测试断言失败:链接不含 auth 参数')
+ return token
+}
+
+/** 本机必须至少存在一个可达地址:环境不满足直接失败,绝不静默跳过(plugin.test.md §7.1)。 */
+function requireReachable(): string {
+ const reachable = enumerateAddresses().filter(item => isReachableAddress(item.address))
+ expect(reachable.length).toBeGreaterThan(0)
+ const address = reachable[0]?.address
+ if (address === undefined)
+ throw new Error('测试断言失败:本机没有可达地址')
+ return address
+}
+
+function ownReachable(): string[] {
+ const found: string[] = []
+ for (const list of Object.values(networkInterfaces())) {
+ for (const info of list ?? []) {
+ if (!info.internal && isReachableAddress(info.address))
+ found.push(info.address)
+ }
+ }
+ return found
+}
+
+beforeEach(async () => {
+ resetPairingCode()
+ previousHome = process.env.DSH_HOME
+ previousPort = process.env.DSH_WEB_PORT
+ process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'dsh-remote-access-service-'))
+ homes.push(process.env.DSH_HOME)
+ upstream = await startUpstream()
+ mintAuthorities = []
+ process.env.DSH_WEB_PORT = String(upstream.port)
+ setCurrentHostInstance({
+ webServer: { register: () => () => {} },
+ effect: () => {},
+ connection: {
+ authenticatedUrl: (base: string) => {
+ mintAuthorities.push(new URL(base).host)
+ return `${base}?token=launch-token`
+ },
+ },
+ } as unknown as RemoteHostContext)
+})
+
+afterEach(async () => {
+ await access.dispose()
+ await gateway.dispose()
+ await upstream.close()
+ setCurrentHostInstance(undefined)
+ if (previousHome === undefined)
+ delete process.env.DSH_HOME
+ else
+ process.env.DSH_HOME = previousHome
+ if (previousPort === undefined)
+ delete process.env.DSH_WEB_PORT
+ else
+ process.env.DSH_WEB_PORT = previousPort
+ for (const home of homes.splice(0))
+ rmSync(home, { recursive: true, force: true })
+ resetPairingCode()
+ vi.restoreAllMocks()
+})
+
+function storedDocument(): RemoteAccessDocument {
+ return readAccessDocument().document
+}
+
+function documentFile(): string {
+ return join(process.env.DSH_HOME ?? '', 'remote', 'access.json')
+}
+
+async function enable(address = '127.0.0.1', port?: number): Promise<RemoteAccessStatus> {
+ return await access.apply({ enabled: true, address, port: port ?? await freePort() })
+}
+
+describe('access 监听生命周期', () => {
+ it('apply 开启回环监听后网关真实转发到本机 DSH 上游并注入原生 cookie', async () => {
+ const status = await enable()
+ expect(status.listening).toBe(true)
+ expect(status.state).toBe('listening')
+ expect(status.port).toBe(status.listen.port)
+ expect(status.link).toBe(`http://127.0.0.1:${status.port}/`)
+ const reply = await call(status.port, '/')
+ expect(reply.status).toBe(200)
+ expect(reply.body).toBe('<html>dsh</html>')
+ const forwarded = upstream.calls.find(entry => entry.url === '/')
+ expect(mintAuthorities).toEqual([`127.0.0.1:${upstream.port}`])
+ expect(forwarded?.cookie).toContain('dsh-auth-probe=granted')
+ })
+
+ it('回环监听也生成二维码并标注链接来源', async () => {
+ const status = await enable()
+ expect(status.qr).toMatch(/^data:image\/png;base64,/u)
+ expect(status.linkSource).toBe('loopback')
+ expect(status.error).toBeUndefined()
+ expect(status.maskLink).toBe(`http://127.0.0.1:${status.port}/`)
+ })
+
+ it('开启暴露时没有凭据就自动生成随机强密码并自动开认证', async () => {
+ const status = await enable()
+ expect(status.generatedPassword).toMatch(/^[2-9A-HJ-NP-Za-km-z]{20}$/u)
+ expect(status.auth.enabled).toBe(true)
+ expect(status.auth.hasPassword).toBe(true)
+ expect(JSON.stringify(storedDocument())).not.toContain(status.generatedPassword ?? '')
+ expect((await access.status()).generatedPassword).toBeUndefined()
+ })
+
+ it('已有凭据时不覆盖,且不把明文写进事件环', async () => {
+ await access.apply({ password: 'keep-me-please' })
+ const status = await enable()
+ expect(status.generatedPassword).toBeUndefined()
+ expect(status.auth.hasPassword).toBe(true)
+ expect(status.events.map(event => event.line).join('\n')).not.toContain('keep-me-please')
+ })
+
+ it('ensureAuth 为隧道补齐认证:无凭据时生成、已有密码时只开开关', async () => {
+ const generated = await access.ensureAuth()
+ expect(generated.generatedPassword).toMatch(/^[2-9A-HJ-NP-Za-km-z]{20}$/u)
+ expect((await access.ensureAuth()).generatedPassword).toBeUndefined()
+ expect((await access.status()).auth.enabled).toBe(true)
+ })
+
+ it('access.json 损坏时所有写操作拒绝,且不覆盖原文件', async () => {
+ mkdirSync(dirname(documentFile()), { recursive: true })
+ writeFileSync(documentFile(), '{ not json')
+ const before = readFileSync(documentFile(), 'utf8')
+ await expect(access.apply({ enabled: true })).rejects.toThrowError('解析失败')
+ await expect(access.rotate()).rejects.toThrowError('解析失败')
+ await expect(access.revoke()).rejects.toThrowError('解析失败')
+ await expect(access.ensureAuth()).rejects.toThrowError('解析失败')
+ expect(readFileSync(documentFile(), 'utf8')).toBe(before)
+ })
+
+ it('关闭暴露后立即停止监听,且再次启动不自动开启', async () => {
+ const status = await enable()
+ const stopped = await access.apply({ enabled: false })
+ expect(stopped.listening).toBe(false)
+ expect(stopped.state).toBe('stopped')
+ expect(stopped.link).toBeUndefined()
+ expect(storedDocument().enabled).toBe(false)
+ await expect(call(status.port, '/')).rejects.toThrowError()
+ await access.dispose()
+ await access.restore()
+ expect((await access.status()).listening).toBe(false)
+ })
+
+ it('端口被占用时回落到下一个可用端口,链接与二维码都用真实端口', async () => {
+ const address = requireReachable()
+ const port = await freePort()
+ const release = await occupy(address, port)
+ try {
+ const status = await enable(address, port)
+ expect(status.port).toBe(port + 1)
+ expect(status.listen.port).toBe(port)
+ const host = address.includes(':') ? `[${address}]` : address
+ expect(status.link).toBe(`http://${host}:${port + 1}/`)
+ expect(status.maskLink).toBe(`http://${host}:${port + 1}/`)
+ expect(status.qr).toBe(await toDataURL(`http://${host}:${port + 1}/`))
+ expect(storedDocument().listen.port).toBe(port)
+ }
+ finally {
+ await release()
+ }
+ })
+
+ it('候选端口全部被占用时进入 error,并给出含尝试范围的可读原因', async () => {
+ const { base, release } = await occupyRange(PORT_FALLBACK_LIMIT + 1)
+ try {
+ const status = await access.apply({ enabled: true, address: '127.0.0.1', port: base })
+ expect(status.listening).toBe(false)
+ expect(status.state).toBe('error')
+ expect(status.error).toContain(`已尝试 ${base}-${base + PORT_FALLBACK_LIMIT}`)
+ expect(status.link).toBeUndefined()
+ expect(status.events.at(-1)?.line).toContain('入站暴露未开启')
+ }
+ finally {
+ await release()
+ }
+ })
+
+ it('选择全部网卡时链接使用本机评分最高的可达地址,绝不出现 0.0.0.0', async () => {
+ const port = await freePort()
+ const status = await enable('0.0.0.0', port)
+ expect(status.listening).toBe(true)
+ expect(status.recommended).toBe(status.addresses.find(item => item.recommended)?.address)
+ expect(ownReachable()).toContain(status.recommended)
+ expect(status.link).not.toContain('0.0.0.0')
+ expect(status.link).toContain(`:${status.port}/`)
+ expect(status.qr).toBe(await toDataURL(status.link ?? ''))
+ })
+
+ it('暴露到非回环地址且没有凭据时自动生成密码,并在事件里写明', async () => {
+ const address = requireReachable()
+ const port = await freePort()
+ const status = await enable(address, port)
+ expect(status.state).toBe('listening')
+ expect(status.auth.hasPassword).toBe(true)
+ const notice = status.events.find(event => event.kind === 'auth')
+ expect(notice?.line).toContain('已自动生成随机强密码')
+ })
+
+ it('显式关掉认证再暴露时,仍对公网与隧道来源给出未配置引导', async () => {
+ const address = requireReachable()
+ const port = await freePort()
+ await access.apply({ password: 'explicit-close-pass', authEnabled: false, enabled: true, address, port })
+ const status = await access.status()
+ expect(status.state).toBe('listening')
+ expect(status.auth.enabled).toBe(false)
+ const warning = status.events.find(event => event.kind === 'auth')
+ expect(warning?.line).toContain('未配置访问密码或链接 Token')
+ })
+
+ it('重启后按上次的 enabled 与监听配置自动恢复', async () => {
+ const port = await freePort()
+ const applied = await enable('127.0.0.1', port)
+ await access.dispose()
+ await access.restore()
+ const restored = await access.status()
+ expect(restored.listening).toBe(true)
+ expect(restored.port).toBe(applied.port)
+ expect(restored.link).toBe(applied.link)
+ const stored = storedDocument()
+ expect({ ...stored, auth: { ...stored.auth, enabled: false, password: null } })
+ .toEqual({ ...defaultAccessDocument(), enabled: true, listen: { address: '127.0.0.1', port } })
+ expect(stored.auth.password).not.toBeNull()
+ })
+
+ it('恢复失败时保持关闭并给出可读原因,且不静默改写配置', async () => {
+ writeAccessDocument({ ...defaultAccessDocument(), enabled: true, listen: { address: '203.0.113.7', port: 3088 } })
+ await expect(access.restore()).resolves.toBeUndefined()
+ const status = await access.status()
+ expect(status.listening).toBe(false)
+ expect(status.state).toBe('error')
+ expect(status.error).toContain('已不存在')
+ expect(storedDocument()).toEqual({ ...defaultAccessDocument(), enabled: true, listen: { address: '203.0.113.7', port: 3088 } })
+ })
+
+ it('缺少 DSH_WEB_PORT 时用宿主 webserver 的实监听端口作为上游(非桌面载体)', async () => {
+ delete process.env.DSH_WEB_PORT
+ setCurrentHostInstance({
+ webServer: { register: () => () => {}, port: upstream.port },
+ effect: () => {},
+ connection: {
+ authenticatedUrl: (base: string) => {
+ mintAuthorities.push(new URL(base).host)
+ return `${base}?token=launch-token`
+ },
+ },
+ } as unknown as RemoteHostContext)
+ const status = await enable()
+ expect(status.listening).toBe(true)
+ expect(status.localPort).toBe(upstream.port)
+ const reply = await call(status.port, '/')
+ expect(reply.status).toBe(200)
+ expect(reply.body).toBe('<html>dsh</html>')
+ })
+
+ it('宿主 webserver 与 DSH_WEB_PORT 都缺失时明确报错而不是硬编码上游端口', async () => {
+ delete process.env.DSH_WEB_PORT
+ const status = await access.apply({ enabled: true })
+ expect(status.listening).toBe(false)
+ expect(status.state).toBe('error')
+ expect(status.error).toContain('DSH_WEB_PORT')
+ })
+
+ it('损坏的 access.json 不阻断恢复,且文件保留在磁盘上', async () => {
+ mkdirSync(dirname(documentFile()), { recursive: true })
+ writeFileSync(documentFile(), '{ broken')
+ await expect(access.restore()).resolves.toBeUndefined()
+ const status = await access.status()
+ expect(status.listening).toBe(false)
+ expect(status.error).toContain('解析失败')
+ expect(status.warnings?.[0]).toContain('解析失败')
+ expect(readFileSync(documentFile(), 'utf8')).toBe('{ broken')
+ })
+})
+
+describe('access 临时码消费与长轮询(真实路由和网关)', () => {
+ it('宿主策略消费成功后响应新码和 usedSeq,永久凭据及既有会话保持不变', async () => {
+ const status = await enable()
+ const first = status.pairing
+ expect(first).toMatchObject({ usedSeq: 0 })
+ const document = readFileSync(documentFile(), 'utf8')
+ const login = await signIn(status.port, first?.code.toLowerCase() ?? '')
+ expect(login.status).toBe(302)
+ const next = await access.status()
+ expect(next.pairing?.usedSeq).toBe(1)
+ expect(next.pairing?.code).not.toBe(first?.code)
+ expect(readFileSync(documentFile(), 'utf8')).toBe(document)
+ expect((await signIn(status.port, first?.code ?? '')).status).toBe(401)
+ expect((await call(status.port, '/api/probe', { source: 'public', cookie: sessionCookieOf(login.headers) })).status).toBe(200)
+ expect((await access.status()).pairing?.usedSeq).toBe(1)
+ })
+
+ it('回环 GET/access 在临时码消费后立即唤醒,迟到的 cursor 直接返回', async () => {
+ const status = await enable()
+ const timers = vi.spyOn(globalThis, 'setTimeout')
+ const path = '/api/tauri/remote/access?sincePairingUseSeq=0'
+ const pending = call(upstream.port, path)
+ await vi.waitFor(() => expect(timers.mock.calls.some(([, delay]) => delay === 8000)).toBe(true))
+ expect((await signIn(status.port, status.pairing?.code.toLowerCase() ?? '')).status).toBe(302)
+ const reply = await pending
+ expect(reply.status).toBe(200)
+ expect(JSON.parse(reply.body).pairing).toMatchObject({ usedSeq: 1 })
+ expect(JSON.parse(reply.body).pairing.code).not.toBe(status.pairing?.code)
+ timers.mockClear()
+ const late = await call(upstream.port, path)
+ expect(late.status).toBe(200)
+ expect(JSON.parse(late.body).pairing.usedSeq).toBe(1)
+ expect(timers.mock.calls.some(([, delay]) => delay === 8000)).toBe(false)
+ })
+
+ it('gET/access 验证安全整数 cursor,非回环及伪造来源拒绝且不等待', async () => {
+ await enable()
+ for (const cursor of ['', '-1', '1.5', 'oops', '9007199254740992', 'Infinity', '0&sincePairingUseSeq=0']) {
+ const reply = await call(upstream.port, `/api/tauri/remote/access?sincePairingUseSeq=${cursor}`)
+ expect(reply.status).toBe(400)
+ expect(JSON.parse(reply.body).message).toBe('invalid sincePairingUseSeq')
+ }
+ const timers = vi.spyOn(globalThis, 'setTimeout')
+ for (const source of ['public', 'private', 'tunnel']) {
+ const reply = await call(upstream.port, '/api/tauri/remote/access?sincePairingUseSeq=0', { source })
+ expect(reply.status).toBe(403)
+ expect(JSON.parse(reply.body)).toEqual({ error: '管理接口仅限本机回环来源' })
+ }
+ const forged = await fetch(`http://127.0.0.1:${upstream.port}/api/tauri/remote/access?sincePairingUseSeq=0`, { headers: { 'connection': 'close', 'x-dsh-remote-source': 'loopback', 'x-dsh-remote-session': 'forged' } })
+ expect(forged.status).toBe(403)
+ expect(await forged.json()).toEqual({ error: '管理接口仅限本机回环来源' })
+ expect(timers.mock.calls.some(([, delay]) => delay === 8000)).toBe(false)
+ })
+
+ it('gET/access 长轮询客户端取消时清理定时器,dispose 结束残留等待', async () => {
+ await enable()
+ const timers = vi.spyOn(globalThis, 'setTimeout')
+ const cleared = vi.spyOn(globalThis, 'clearTimeout')
+ const controller = new AbortController()
+ const pending = fetch(`http://127.0.0.1:${upstream.port}/api/tauri/remote/access?sincePairingUseSeq=0`, { headers: { connection: 'close' }, signal: controller.signal })
+ const cancelled = pending.catch((error: unknown) => error)
+ try {
+ await vi.waitFor(() => expect(timers.mock.calls.some(([, delay]) => delay === 8000)).toBe(true))
+ }
+ finally {
+ controller.abort()
+ }
+ const timer = timers.mock.results[timers.mock.calls.findIndex(([, delay]) => delay === 8000)]?.value
+ expect(await cancelled).toMatchObject({ name: 'AbortError' })
+ await vi.waitFor(() => expect(cleared.mock.calls.some(([handle]) => handle === timer)).toBe(true))
+ timers.mockClear()
+ const remaining = call(upstream.port, '/api/tauri/remote/access?sincePairingUseSeq=0')
+ await vi.waitFor(() => expect(timers.mock.calls.some(([, delay]) => delay === 8000)).toBe(true))
+ await access.dispose()
+ expect((await remaining).status).toBe(200)
+ expect(pairingCodeOf().usedSeq).toBe(0)
+ })
+
+ it('tTL 自动轮换不记为消费,长轮询八秒超时仍返回最新状态', async () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000)
+ const status = await enable()
+ expect(status.pairing?.usedSeq).toBe(0)
+ const timers = vi.spyOn(globalThis, 'setTimeout')
+ const pending = call(upstream.port, '/api/tauri/remote/access?sincePairingUseSeq=0')
+ await vi.waitFor(() => expect(timers.mock.calls.some(([, delay]) => delay === 8000)).toBe(true))
+ clock.mockReturnValue(status.pairing?.expiresAt ?? 0)
+ const reply = await pending
+ expect(reply.status).toBe(200)
+ expect(JSON.parse(reply.body).pairing.usedSeq).toBe(0)
+ expect(JSON.parse(reply.body).pairing.code).not.toBe(status.pairing?.code)
+ expect(consumePairingCode(JSON.parse(reply.body).pairing.code)).toBe(true)
+ expect(pairingCodeOf().usedSeq).toBe(1)
+ })
+})
+
+describe('access 认证与来源判定(经真实网关)', () => {
+ it('开启暴露即自动带凭据:私网免密放行,公网与隧道来源进入登录而非未配置引导', async () => {
+ const status = await enable()
+ expect(status.auth.hasPassword).toBe(true)
+ expect((await call(status.port, '/api/probe', { source: 'private' })).status).toBe(200)
+ const publicReply = await call(status.port, '/api/probe', { source: 'public' })
+ expect(publicReply.status).toBe(401)
+ expect(publicReply.body).toContain('需要认证')
+ const loginPage = await call(status.port, '/', { source: 'public', form: undefined })
+ expect(loginPage.status).toBe(401)
+ expect((await call(status.port, '/api/probe', { source: 'tunnel' })).status).toBe(401)
+ })
+
+ it('用户显式关掉认证后,公网与隧道来源回到未配置引导并拒绝', async () => {
+ const status = await enable()
+ await access.apply({ authEnabled: false })
+ const publicReply = await call(status.port, '/api/probe', { source: 'public' })
+ expect(publicReply.status).toBe(403)
+ expect(publicReply.body).toContain('尚未配置访问认证')
+ expect((await call(status.port, '/api/probe', { source: 'tunnel' })).status).toBe(403)
+ })
+
+ it('scope=public_only 时私网免密、公网要求认证;scope=all 时私网也要求认证', async () => {
+ const status = await enable()
+ await access.apply({ authEnabled: true, password: 'hunter2', scope: 'public_only' })
+ expect((await call(status.port, '/api/probe', { source: 'private' })).status).toBe(200)
+ expect((await call(status.port, '/api/probe', { source: 'public' })).status).toBe(401)
+ await access.apply({ scope: 'all' })
+ expect((await call(status.port, '/api/probe', { source: 'private' })).status).toBe(401)
+ })
+
+ it('链接 Token 可换到会话并 302 到干净 URL,轮换后旧链接立即失效', async () => {
+ const status = await enable()
+ await access.apply({ authEnabled: true, scope: 'all' })
+ const rotated = await access.rotate()
+ const first = tokenOf(rotated.link)
+ const exchanged = await call(status.port, `/?auth=${first}`, { source: 'public' })
+ expect(exchanged.status).toBe(302)
+ expect(exchanged.headers.location).toBe('/')
+ const cookie = sessionCookieOf(exchanged.headers)
+ expect((await call(status.port, '/api/probe', { source: 'public', cookie })).status).toBe(200)
+
+ const next = await access.rotate()
+ const second = tokenOf(next.link)
+ expect(second).not.toBe(first)
+ expect((await call(status.port, `/?auth=${first}`, { source: 'public' })).status).toBe(401)
+ const again = await call(status.port, `/?auth=${second}`, { source: 'public' })
+ expect(again.status).toBe(302)
+ expect(again.headers.location).toBe('/')
+ })
+
+ it('作废 Token 后旧链接失效,已签发的会话不受影响', async () => {
+ const status = await enable()
+ await access.apply({ authEnabled: true, password: 'hunter2', scope: 'public_only' })
+ const rotated = await access.rotate()
+ const token = tokenOf(rotated.link)
+ const exchanged = await call(status.port, `/?auth=${token}`, { source: 'public' })
+ const cookie = sessionCookieOf(exchanged.headers)
+ const revoked = await access.revoke()
+ expect(revoked.auth.hasToken).toBe(false)
+ expect(revoked.link).toBe(`http://127.0.0.1:${status.port}/`)
+ expect((await call(status.port, `/?auth=${token}`, { source: 'public' })).status).toBe(401)
+ expect((await call(status.port, '/api/probe', { source: 'public', cookie })).status).toBe(200)
+ })
+
+ it('密码连续错误达阈值后封禁并返回可读剩余时间', async () => {
+ const status = await enable()
+ await access.apply({ authEnabled: true, password: 'hunter2', scope: 'public_only' })
+ const attempts: number[] = []
+ for (let index = 0; index < 5; index++)
+ attempts.push((await signIn(status.port, 'wrong')).status)
+ expect(attempts).toEqual([401, 401, 401, 401, 429])
+ const banned = await signIn(status.port, 'hunter2')
+ expect(banned.status).toBe(429)
+ expect(banned.body).toContain('认证失败次数过多')
+ })
+
+ it('保存时丢弃未知键并告警,其余键保留且不整体覆盖为默认值', async () => {
+ mkdirSync(dirname(documentFile()), { recursive: true })
+ writeFileSync(documentFile(), `${JSON.stringify({ version: 1, enabled: false, listen: { address: '127.0.0.1', port: 3300 }, rogue: true }, null, 2)}\n`)
+ const status = await access.apply({ authEnabled: true })
+ expect(status.listen.port).toBe(3300)
+ expect(status.auth.enabled).toBe(true)
+ expect(status.events.map(event => event.line)).toContain('access.json 丢弃未知键 rogue')
+ expect(Object.keys(JSON.parse(readFileSync(documentFile(), 'utf8')))).toEqual(['version', 'enabled', 'listen', 'auth', 'tunnel'])
+ })
+
+ it('密码只以哈希落盘且校验通过,明文不出现在配置文档里', async () => {
+ await access.apply({ password: 'hunter2' })
+ const password = storedDocument().auth.password
+ expect(password?.algo).toBe('pbkdf2-sha256')
+ expect(verifyPassword('hunter2', password)).toBe(true)
+ expect(readFileSync(documentFile(), 'utf8')).not.toContain('hunter2')
+ const cleared = await access.apply({ password: null })
+ expect(cleared.auth.hasPassword).toBe(false)
+ expect(storedDocument().auth.password).toBeNull()
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/host/service/access.ts b/packages/dsh-tauri-remote/src/host/service/access.ts
new file mode 100644
index 00000000..2e99038d
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/access.ts
@@ -0,0 +1,219 @@
+import type { RemoteAuthPolicy } from '../types/index'
+import type { RemoteAccessBody, RemoteAccessDocument, RemoteAccessEvent, RemoteAccessEventKind, RemoteAccessState, RemoteAccessStatus } from './access.types'
+import { defineService } from 'dsh-tauri'
+import { toDataURL } from 'qrcode'
+import { messageOf } from '../../shared/error'
+import { hostServicePort, localUpstream, mintAuthenticatedUrl } from '../config/runtime'
+import { createLinkToken, createSessionSecret, generateAccessPassword, hashPassword } from '../utils/auth'
+import { isAuthConfigured } from '../utils/source'
+import { addressProblemOf, buildLink, buildTunnelLink, enumerateAddresses, isLoopbackListen, linkHostOf, maskLinkOf, pairingLinksOf, patchAccessDocument, policyOf, readAccessDocument, writeAccessDocument } from './access.utils'
+import { gateway } from './gateway'
+import { consumePairingCode, pairingCodeOf, resetPairingCode } from './pairing'
+import { tunnel } from './tunnel'
+
+const ENTRY_ID = 'inbound'
+
+const EVENT_CAPACITY = 50
+
+const NO_LOCAL_PORT = '无法确定本机 DSH 端口(宿主 webserver 未暴露端口且进程缺少 DSH_WEB_PORT),未开启入站暴露'
+
+const CORRUPT_DOCUMENT = 'access.json 解析失败:已按未配置处理,写操作被拒绝以免覆盖原文件(请先修复或移走该文件)'
+
+const SESSION_SECRET = createSessionSecret()
+
+let failure: string | undefined
+
+let sequence = 0
+
+let events: RemoteAccessEvent[] = []
+
+export const access = defineService({
+ /** 网关每次判定都重新取用:配置与凭据变更立即生效(S2 §7.4)。 */
+ policy(): RemoteAuthPolicy {
+ return { ...policyOf(readAccessDocument().document, SESSION_SECRET), pairingCode: pairingCodeOf().code, consumePairingCode }
+ },
+
+ async status(): Promise<RemoteAccessStatus> {
+ const parsed = readAccessDocument()
+ const document = parsed.document
+ const addresses = enumerateAddresses()
+ const entry = gateway.status(ENTRY_ID)
+ const listening = entry?.state === 'listening'
+ const port = listening ? entry.port : 0
+ const problem = failure ?? (document.enabled ? addressProblemOf(document.listen.address, addresses) : undefined)
+ const host = listening ? linkHostOf(document.listen.address, addresses) : undefined
+ const link = host === undefined || port === 0 ? undefined : buildLink(host, port, document.auth.token)
+ const recommended = addresses.find(item => item.recommended)?.address
+ const local = hostServicePort()
+ const tunnelStatus = await tunnel.status()
+ const tunnelLink = tunnelStatus.url === undefined ? undefined : buildTunnelLink(tunnelStatus.url, document.auth.token)
+ const state: RemoteAccessState = problem !== undefined ? 'error' : listening ? 'listening' : 'stopped'
+ const status: RemoteAccessStatus = {
+ version: document.version,
+ enabled: document.enabled,
+ state,
+ listening,
+ listen: document.listen,
+ port,
+ auth: {
+ enabled: document.auth.enabled,
+ scope: document.auth.scope,
+ hasPassword: document.auth.password !== null,
+ hasToken: document.auth.token !== null,
+ ...document.auth.token === null ? {} : { token: document.auth.token },
+ },
+ addresses,
+ events: [...events],
+ ...recommended === undefined ? {} : { recommended },
+ ...link === undefined ? {} : { link },
+ ...host === undefined || port === 0 ? {} : { maskLink: maskLinkOf(host, port, document.auth.token !== null) },
+ tunnel: tunnelLink === undefined ? tunnelStatus : { ...tunnelStatus, link: tunnelLink, qr: await toDataURL(tunnelLink) },
+ ...local === undefined ? {} : { localPort: local },
+ ...problem === undefined ? {} : { error: problem },
+ ...parsed.warnings.length === 0 ? {} : { warnings: parsed.warnings },
+ }
+ if (link !== undefined) {
+ status.qr = await toDataURL(link)
+ status.linkSource = isLoopbackListen(document.listen.address) ? 'loopback' : 'lan'
+ }
+ const pairing = pairingCodeOf()
+ const pairingLinks = pairingLinksOf({ code: pairing.code, host, port, tunnelUrl: tunnelStatus.url })
+ if (pairingLinks.link !== undefined || pairingLinks.tunnelLink !== undefined) {
+ status.pairing = {
+ ...pairing,
+ ...pairingLinks.link === undefined ? {} : { link: pairingLinks.link, qr: await toDataURL(pairingLinks.link) },
+ ...pairingLinks.tunnelLink === undefined ? {} : { tunnelLink: pairingLinks.tunnelLink, tunnelQr: await toDataURL(pairingLinks.tunnelLink) },
+ }
+ }
+ return status
+ },
+
+ async apply(body: RemoteAccessBody): Promise<RemoteAccessStatus> {
+ const parsed = readAccessDocument()
+ if (parsed.corrupt)
+ throw new Error(CORRUPT_DOCUMENT)
+ for (const warning of parsed.warnings)
+ note('state', warning)
+ const patched = patchAccessDocument(parsed.document, body, enumerateAddresses())
+ const generatedPassword = patched.enabled ? autoPasswordOf(patched) : undefined
+ const next = generatedPassword === undefined ? patched : withGeneratedPassword(patched, generatedPassword)
+ writeAccessDocument(next)
+ await activate(next)
+ return { ...await access.status(), ...generatedPassword === undefined ? {} : { generatedPassword } }
+ },
+
+ /** 公网隧道前置:认证未开则开;没有可用凭据则自动生成密码(返回明文供面板一次性展示)。 */
+ async ensureAuth(): Promise<RemoteAccessStatus> {
+ const parsed = readAccessDocument()
+ if (parsed.corrupt)
+ throw new Error(CORRUPT_DOCUMENT)
+ const generatedPassword = autoPasswordOf(parsed.document)
+ const next = generatedPassword === undefined
+ ? { ...parsed.document, auth: { ...parsed.document.auth, enabled: true } }
+ : withGeneratedPassword(parsed.document, generatedPassword)
+ writeAccessDocument(next)
+ await activate(next)
+ return { ...await access.status(), ...generatedPassword === undefined ? {} : { generatedPassword } }
+ },
+
+ async rotate(): Promise<RemoteAccessStatus> {
+ const parsed = readAccessDocument()
+ if (parsed.corrupt)
+ throw new Error(CORRUPT_DOCUMENT)
+ writeAccessDocument({ ...parsed.document, auth: { ...parsed.document.auth, token: createLinkToken() } })
+ note('token', '链接 Token 已轮换,旧链接立即失效(已签发的会话不受影响)')
+ return await access.status()
+ },
+
+ async revoke(): Promise<RemoteAccessStatus> {
+ const parsed = readAccessDocument()
+ if (parsed.corrupt)
+ throw new Error(CORRUPT_DOCUMENT)
+ writeAccessDocument({ ...parsed.document, auth: { ...parsed.document.auth, token: null } })
+ note('token', '链接 Token 已作废,已签发的会话不受影响')
+ return await access.status()
+ },
+
+ async restore(): Promise<void> {
+ const parsed = readAccessDocument()
+ if (parsed.corrupt) {
+ failure = parsed.warnings[0]
+ note('state', failure ?? 'access.json 解析失败')
+ return
+ }
+ for (const warning of parsed.warnings)
+ note('state', warning)
+ if (!parsed.document.enabled) {
+ failure = undefined
+ return
+ }
+ await activate(parsed.document)
+ },
+
+ async dispose(): Promise<void> {
+ resetPairingCode()
+ await gateway.stop(ENTRY_ID)
+ failure = undefined
+ events = []
+ },
+})
+
+// --- internal ---
+/** 只在完全没有凭据时生成:已有密码或链接 Token 说明用户已做过选择,认证开关本身不再被改写。 */
+function autoPasswordOf(document: RemoteAccessDocument): string | undefined {
+ const auth = document.auth
+ return auth.password === null && auth.token === null ? generateAccessPassword() : undefined
+}
+
+function withGeneratedPassword(document: RemoteAccessDocument, password: string): RemoteAccessDocument {
+ note('auth', '未设置访问密码:已自动生成随机强密码并开启访问认证(明文仅在面板显示一次)')
+ return { ...document, auth: { ...document.auth, enabled: true, password: hashPassword(password) } }
+}
+
+async function activate(document: RemoteAccessDocument): Promise<void> {
+ if (!document.enabled) {
+ await gateway.stop(ENTRY_ID)
+ failure = undefined
+ note('state', '入站暴露已关闭')
+ return
+ }
+ const upstream = localUpstream()
+ if (upstream === undefined) {
+ await fail(NO_LOCAL_PORT)
+ return
+ }
+ const problem = addressProblemOf(document.listen.address, enumerateAddresses())
+ if (problem !== undefined) {
+ await fail(problem)
+ return
+ }
+ try {
+ const entry = await gateway.start({
+ id: ENTRY_ID,
+ kind: 'inbound',
+ upstream,
+ port: document.listen.port,
+ host: document.listen.address,
+ tokenProvider: mintAuthenticatedUrl,
+ auth: () => access.policy(),
+ })
+ failure = undefined
+ note('state', `入站暴露已监听 ${entry.host}:${entry.port}`)
+ if (!isLoopbackListen(document.listen.address) && !isAuthConfigured(access.policy()))
+ note('auth', '未配置访问密码或链接 Token:公网与隧道来源将被 403 拒绝,私网来源可直连')
+ }
+ catch (error) {
+ await fail(messageOf(error))
+ }
+}
+
+async function fail(reason: string): Promise<void> {
+ failure = reason
+ await gateway.stop(ENTRY_ID)
+ note('state', `入站暴露未开启:${reason}`)
+}
+
+function note(kind: RemoteAccessEventKind, line: string): void {
+ sequence += 1
+ events = [...events, { seq: sequence, ts: new Date().toISOString(), kind, line }].slice(-EVENT_CAPACITY)
+}
diff --git a/packages/dsh-tauri-remote/src/host/service/access.types.ts b/packages/dsh-tauri-remote/src/host/service/access.types.ts
new file mode 100644
index 00000000..9456ec01
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/access.types.ts
@@ -0,0 +1,108 @@
+import type { RemoteAuthScope, RemotePasswordRecord, RemoteTunnelConfig, RemoteTunnelStatus } from '../types/index'
+
+export interface RemoteAccessListen {
+ address: string
+ port: number
+}
+
+export interface RemoteAccessAuthDocument {
+ enabled: boolean
+ password: RemotePasswordRecord | null
+ token: string | null
+ scope: RemoteAuthScope
+}
+
+export interface RemoteAccessDocument {
+ version: number
+ enabled: boolean
+ listen: RemoteAccessListen
+ auth: RemoteAccessAuthDocument
+ tunnel: RemoteTunnelConfig
+}
+
+/** `POST /access` 请求体:字段缺省表示保持原值(`password` 只写,`null` 表示清除已设密码)。 */
+export interface RemoteAccessBody {
+ enabled?: boolean
+ address?: string
+ port?: number
+ authEnabled?: boolean
+ scope?: RemoteAuthScope
+ password?: string | null
+}
+
+export type RemoteLinkSource = 'loopback' | 'lan'
+
+export type RemoteAccessState = 'stopped' | 'listening' | 'error'
+
+export type RemoteAddressFamily = 'ipv4' | 'ipv6'
+
+export type RemoteAddressScope = 'loopback' | 'private' | 'public' | 'link-local'
+
+export interface RemoteAccessAddress {
+ address: string
+ family: RemoteAddressFamily
+ interface: string
+ scope: RemoteAddressScope
+ score: number
+ recommended: boolean
+}
+
+export type RemoteAccessEventKind = 'state' | 'auth' | 'token'
+
+export interface RemoteAccessEvent {
+ seq: number
+ ts: string
+ kind: RemoteAccessEventKind
+ line: string
+}
+
+/** 临时配对码:宿主生成、5 分钟轮换;分享链接与二维码只携带它,永久凭据不出现在分享物里(评审意见 6)。 */
+export interface RemoteAccessPairing {
+ code: string
+ expiresAt: number
+ usedSeq: number
+ /** 局域网入口的短期链接与二维码;监听未开启时缺省(此时只有隧道入口可用)。 */
+ link?: string
+ qr?: string
+ /** 隧道就绪时附带的同一临时码公网链接与二维码;隧道未运行则缺省。 */
+ tunnelLink?: string
+ tunnelQr?: string
+}
+
+export interface RemoteAccessStatus {
+ version: number
+ enabled: boolean
+ state: RemoteAccessState
+ listening: boolean
+ /** 配置值:选定地址与首选端口(回落时保持首选值不变)。 */
+ listen: RemoteAccessListen
+ /** 真实监听端口;未监听时为 0。 */
+ port: number
+ auth: { enabled: boolean, scope: RemoteAuthScope, hasPassword?: boolean, hasToken?: boolean, token?: string }
+ addresses: RemoteAccessAddress[]
+ recommended?: string
+ /** 完整链接(含链接 Token);仅回环来源可见。 */
+ link?: string
+ /** 掩码链接:主机与端口可见、Token 隐藏;非回环来源仅此一项。 */
+ maskLink?: string
+ /** 链接的二维码 dataURL(回环监听也生成:面板用于本地核对与演示)。 */
+ qr?: string
+ /** 链接归属:回环监听 = 仅本机可用,网卡监听 = 局域网可用。 */
+ linkSource?: RemoteLinkSource
+ /** 临时配对码与其分享链接/二维码;仅回环来源可见。 */
+ pairing?: RemoteAccessPairing
+ /** 本次请求刚自动生成的访问密码明文:只在响应里出现一次,不落盘、不进事件环。 */
+ generatedPassword?: string
+ /** 公网隧道读面:配置 + 运行期状态(完整分支才带 Token 与链接二维码)。 */
+ tunnel?: RemoteTunnelStatus
+ localPort?: number
+ error?: string
+ warnings?: string[]
+ events: RemoteAccessEvent[]
+}
+
+export interface RemoteAccessParse {
+ document: RemoteAccessDocument
+ corrupt: boolean
+ warnings: string[]
+}
diff --git a/packages/dsh-tauri-remote/src/host/service/access.utils.test.ts b/packages/dsh-tauri-remote/src/host/service/access.utils.test.ts
new file mode 100644
index 00000000..c5a4366e
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/access.utils.test.ts
@@ -0,0 +1,427 @@
+import type { NetworkInterfaceInfo } from 'node:os'
+import type { RemoteAccessAddress, RemoteAccessStatus } from './access.types'
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'pathe'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { verifyPassword } from '../utils/auth'
+import { ACCESS_DOCUMENT_VERSION, addressProblemOf, buildLink, DEFAULT_ACCESS_ADDRESS, DEFAULT_ACCESS_PORT, defaultAccessDocument, enumerateAddresses, isReachableAddress, isSelectableAddress, linkHostOf, maskLinkOf, pairingLinksOf, parseAccessDocument, patchAccessDocument, policyOf, rankAddresses, readAccessDocument, redactStatus, serializeAccessDocument, writeAccessDocument } from './access.utils'
+
+const homes: string[] = []
+
+let previousHome: string | undefined
+
+beforeEach(() => {
+ previousHome = process.env.DSH_HOME
+ const home = mkdtempSync(join(tmpdir(), 'dsh-remote-access-'))
+ homes.push(home)
+ process.env.DSH_HOME = home
+})
+
+afterEach(() => {
+ if (previousHome === undefined)
+ delete process.env.DSH_HOME
+ else
+ process.env.DSH_HOME = previousHome
+ for (const home of homes.splice(0))
+ rmSync(home, { recursive: true, force: true })
+})
+
+function accessFile(): string {
+ return join(process.env.DSH_HOME ?? '', 'remote', 'access.json')
+}
+
+function writeAccessFile(text: string): void {
+ mkdirSync(dirname(accessFile()), { recursive: true })
+ writeFileSync(accessFile(), text)
+}
+
+function v4(address: string, internal = false): NetworkInterfaceInfo {
+ return { address, netmask: '255.255.255.0', family: 'IPv4', mac: '00:00:00:00:00:00', internal, cidr: `${address}/24` }
+}
+
+function v6(address: string, internal = false): NetworkInterfaceInfo {
+ return { address, netmask: 'ffff:ffff:ffff:ffff::', family: 'IPv6', mac: '00:00:00:00:00:00', internal, cidr: `${address}/64`, scopeid: 0 }
+}
+
+function entry(address: string, overrides: Partial<RemoteAccessAddress> = {}): RemoteAccessAddress {
+ return {
+ address,
+ family: address.includes(':') ? 'ipv6' : 'ipv4',
+ interface: 'en0',
+ scope: 'private',
+ score: 120,
+ recommended: false,
+ ...overrides,
+ }
+}
+
+function statusFixture(): RemoteAccessStatus {
+ return {
+ version: ACCESS_DOCUMENT_VERSION,
+ enabled: true,
+ state: 'listening',
+ listening: true,
+ listen: { address: '192.168.1.5', port: 3088 },
+ port: 3089,
+ auth: { enabled: true, scope: 'public_only', hasPassword: true, hasToken: true },
+ addresses: [entry('192.168.1.5', { recommended: true })],
+ recommended: '192.168.1.5',
+ link: 'http://192.168.1.5:3089/?auth=secret-token',
+ maskLink: 'http://192.168.1.5:3089/?auth=***',
+ qr: 'data:image/png;base64,QUJD',
+ tunnel: {
+ enabled: true,
+ mode: 'quick',
+ hostname: 'x.trycloudflare.com',
+ token: 'tunnel-secret',
+ state: 'running',
+ events: [{ seq: 1, ts: '2026-10-05T00:00:00.000Z', kind: 'process', line: 'cloudflared 已启动' }],
+ url: 'https://x.trycloudflare.com',
+ port: 3089,
+ link: 'https://x.trycloudflare.com/?auth=secret-token',
+ qr: 'data:image/png;base64,QUJD',
+ },
+ localPort: 3080,
+ error: '示例错误',
+ warnings: ['丢弃未知键 foo'],
+ events: [{ seq: 1, ts: '2026-10-05T00:00:00.000Z', kind: 'state', line: '入站暴露已监听' }],
+ }
+}
+
+describe('parseAccessDocument', () => {
+ it('文件缺失或全为空白时回落默认文档且不算损坏', () => {
+ const missing = parseAccessDocument(undefined)
+ expect(missing.document).toEqual(defaultAccessDocument())
+ expect(missing.corrupt).toBe(false)
+ const blank = parseAccessDocument(' \n')
+ expect(blank.document).toEqual(defaultAccessDocument())
+ expect(blank.corrupt).toBe(false)
+ })
+
+ it('无法解析的 JSON 视为未配置并标记损坏,不抛错', () => {
+ const parsed = parseAccessDocument('{ not json')
+ expect(parsed.corrupt).toBe(true)
+ expect(parsed.document.enabled).toBe(false)
+ expect(parsed.warnings[0]).toContain('解析失败')
+ })
+
+ it('丢弃未知顶层键并告警,已知键照常生效', () => {
+ const parsed = parseAccessDocument(JSON.stringify({ version: 3, enabled: true, listen: { address: '10.0.0.2', port: 4000 }, rogue: 1 }))
+ expect(parsed.warnings).toEqual(['access.json 丢弃未知键 rogue'])
+ expect(parsed.document.version).toBe(3)
+ expect(parsed.document.enabled).toBe(true)
+ expect(parsed.document.listen).toEqual({ address: '10.0.0.2', port: 4000 })
+ })
+
+ it('丢弃 listen / auth 段里的未知键并告警', () => {
+ const parsed = parseAccessDocument(JSON.stringify({ listen: { address: '10.0.0.2', port: 4000, extra: true }, auth: { enabled: true, password: null, token: null, scope: 'all', extra: 1 } }))
+ expect(parsed.warnings).toEqual(['access.json 丢弃未知键 listen.extra', 'access.json 丢弃未知键 auth.extra'])
+ expect(parsed.document.auth.scope).toBe('all')
+ })
+
+ it('非法 scope 回落 public_only 且其余键保留', () => {
+ const parsed = parseAccessDocument(JSON.stringify({ enabled: true, auth: { enabled: true, scope: 'lan_only', token: 'keep-me' } }))
+ expect(parsed.document.auth.scope).toBe('public_only')
+ expect(parsed.document.auth.enabled).toBe(true)
+ expect(parsed.document.auth.token).toBe('keep-me')
+ expect(parsed.document.enabled).toBe(true)
+ expect(parsed.warnings).toEqual(['access.json 的 auth.scope 非法,已回落 public_only'])
+ })
+
+ it('缺键时逐键回落默认值', () => {
+ const parsed = parseAccessDocument('{}')
+ expect(parsed.document.listen.address).toBe(DEFAULT_ACCESS_ADDRESS)
+ expect(parsed.document.listen.port).toBe(DEFAULT_ACCESS_PORT)
+ expect(parsed.document.auth).toEqual({ enabled: false, password: null, token: null, scope: 'public_only' })
+ })
+
+ it('非法 listen.port 与 listen.address 各自回落并告警', () => {
+ const parsed = parseAccessDocument(JSON.stringify({ listen: { address: '', port: 70000 } }))
+ expect(parsed.document.listen).toEqual({ address: DEFAULT_ACCESS_ADDRESS, port: DEFAULT_ACCESS_PORT })
+ expect(parsed.warnings).toEqual(['access.json 的 listen.address 非法,已回落 127.0.0.1', 'access.json 的 listen.port 非法,已回落 3088'])
+ })
+
+ it('tunnel 段按契约逐键解析(token 与 hostname 都保留)', () => {
+ const tunnel = { enabled: true, mode: 'token', token: 'cf-token', hostname: 'dsh.example.com' }
+ const parsed = parseAccessDocument(JSON.stringify({ tunnel }))
+ expect(parsed.document.tunnel).toEqual(tunnel)
+ expect(parsed.warnings).toEqual([])
+ })
+
+ it('tunnel 段的未知键丢弃并告警,非法值逐键回落', () => {
+ const parsed = parseAccessDocument(JSON.stringify({ tunnel: { enabled: 'yes', mode: 'named', extra: 1 } }))
+ expect(parsed.document.tunnel).toEqual({ enabled: false, mode: 'quick', token: null, hostname: null })
+ expect(parsed.warnings).toEqual([
+ 'access.json 丢弃未知键 tunnel.extra',
+ 'access.json 的 tunnel.enabled 非法,已回落 false',
+ 'access.json 的 tunnel.mode 非法,已回落 quick',
+ ])
+ })
+
+ it('非对象的 tunnel 段回落默认并告警', () => {
+ const parsed = parseAccessDocument(JSON.stringify({ tunnel: 'quick' }))
+ expect(parsed.document.tunnel).toEqual({ enabled: false, mode: 'quick', token: null, hostname: null })
+ expect(parsed.warnings).toEqual(['access.json 的 tunnel 非法,已回落默认'])
+ })
+
+ it('形态合法但不可用的密码记录原样保留,供网关判定「认证存储损坏」', () => {
+ const password = { algo: 'pbkdf2-sha256', salt: 'not-base64!!', iterations: 600000, hash: 'short' }
+ const parsed = parseAccessDocument(JSON.stringify({ auth: { enabled: true, password } }))
+ expect(parsed.document.auth.password).toEqual(password)
+ expect(parsed.warnings).toEqual([])
+ })
+
+ it('形态非法的密码记录丢弃并告警', () => {
+ const parsed = parseAccessDocument(JSON.stringify({ auth: { password: { algo: 'sha1', salt: 'x', iterations: 1, hash: 'y' } } }))
+ expect(parsed.document.auth.password).toBeNull()
+ expect(parsed.warnings).toEqual(['access.json 的 auth.password 非法,已丢弃'])
+ })
+
+ it('序列化结果可被原样解析回来', () => {
+ const document = { ...defaultAccessDocument(), enabled: true, listen: { address: '10.0.0.2', port: 4000 } }
+ expect(serializeAccessDocument(document).endsWith('\n')).toBe(true)
+ expect(parseAccessDocument(serializeAccessDocument(document)).document).toEqual(document)
+ })
+})
+
+describe('readAccessDocument / writeAccessDocument', () => {
+ it('落盘为 0600 文件与 0700 目录,且不残留临时文件', () => {
+ writeAccessDocument({ ...defaultAccessDocument(), enabled: true })
+ expect(statSync(accessFile()).mode & 0o777).toBe(0o600)
+ expect(statSync(dirname(accessFile())).mode & 0o777).toBe(0o700)
+ expect(readdirSync(dirname(accessFile()))).toEqual(['access.json'])
+ })
+
+ it('写入后读回同一份文档', () => {
+ const document = { ...defaultAccessDocument(), enabled: true, listen: { address: '192.168.1.5', port: 4100 }, auth: { enabled: true, password: null, token: 'tok', scope: 'all' as const } }
+ writeAccessDocument(document)
+ expect(readAccessDocument().document).toEqual(document)
+ })
+
+ it('解析失败的文件保留在磁盘上供手工修复', () => {
+ writeAccessFile('{ broken')
+ expect(readAccessDocument().corrupt).toBe(true)
+ expect(existsSync(accessFile())).toBe(true)
+ expect(readFileSync(accessFile(), 'utf8')).toBe('{ broken')
+ })
+
+ it('文件不存在时读回默认文档', () => {
+ expect(readAccessDocument().document).toEqual(defaultAccessDocument())
+ expect(readAccessDocument().corrupt).toBe(false)
+ })
+})
+
+describe('enumerateAddresses / rankAddresses', () => {
+ it('物理网卡排在虚拟网卡之前,推荐位落在物理私网地址上', () => {
+ const addresses = enumerateAddresses({
+ docker0: [v4('172.17.0.1')],
+ en0: [v4('192.168.1.5')],
+ })
+ expect(addresses.map(item => item.address)).toEqual(['192.168.1.5', '172.17.0.1'])
+ expect(addresses.find(item => item.recommended)?.address).toBe('192.168.1.5')
+ expect(addresses.every(item => item.interface !== undefined)).toBe(true)
+ })
+
+ it('私网优先于公网、IPv4 优先于 IPv6', () => {
+ const addresses = rankAddresses([
+ entry('203.0.113.7', { scope: 'public', score: 100 }),
+ entry('192.168.1.5', { scope: 'private', score: 120 }),
+ entry('fd00::1', { scope: 'private', score: 115, family: 'ipv6' }),
+ ])
+ expect(addresses.map(item => item.address)).toEqual(['192.168.1.5', 'fd00::1', '203.0.113.7'])
+ expect(addresses.map(item => item.recommended)).toEqual([true, false, false])
+ })
+
+ it('回环地址不进入枚举结果', () => {
+ const addresses = enumerateAddresses({ lo0: [v4('127.0.0.1', true), v6('::1', true)] })
+ expect(addresses).toEqual([])
+ })
+
+ it('仅剩 link-local 时没有任何推荐地址', () => {
+ const addresses = enumerateAddresses({ en0: [v6('fe80::1234%en0'), v4('169.254.10.10')] })
+ expect(addresses).toHaveLength(2)
+ expect(addresses.some(item => item.recommended)).toBe(false)
+ expect(addresses.map(item => item.scope)).toEqual(['link-local', 'link-local'])
+ })
+
+ it('评分把网卡名、地址族与私网属性一起计入', () => {
+ const addresses = enumerateAddresses({
+ utun3: [v6('fd00::9')],
+ en0: [v4('203.0.113.7')],
+ wlan0: [v4('10.1.2.3')],
+ })
+ expect(addresses.map(item => item.address)).toEqual(['10.1.2.3', '203.0.113.7', 'fd00::9'])
+ })
+})
+
+describe('isReachableAddress / linkHostOf / addressProblemOf', () => {
+ it('排除回环、link-local、带 zone id 的地址与 0.0.0.0 / ::', () => {
+ expect(isReachableAddress('192.168.1.5')).toBe(true)
+ expect(isReachableAddress('fd00::1')).toBe(true)
+ expect(isReachableAddress('127.0.0.1')).toBe(false)
+ expect(isReachableAddress('::1')).toBe(false)
+ expect(isReachableAddress('fe80::1')).toBe(false)
+ expect(isReachableAddress('febf::1')).toBe(false)
+ expect(isReachableAddress('169.254.1.1')).toBe(false)
+ expect(isReachableAddress('fd00::1%en0')).toBe(false)
+ expect(isReachableAddress('0.0.0.0')).toBe(false)
+ expect(isReachableAddress('::')).toBe(false)
+ })
+
+ it('通配监听取评分最高的可达地址,绝不产生 0.0.0.0 链接', () => {
+ const addresses = rankAddresses([
+ entry('0.0.0.0', { score: 0 }),
+ entry('10.1.2.3', { score: 125 }),
+ entry('169.254.10.10', { score: 0, scope: 'link-local' }),
+ ])
+ expect(linkHostOf('0.0.0.0', addresses)).toBe('10.1.2.3')
+ expect(linkHostOf('::', addresses)).toBe('10.1.2.3')
+ expect(addressProblemOf('0.0.0.0', addresses)).toBeUndefined()
+ })
+
+ it('具体对外地址用其本身,回环监听用回环地址', () => {
+ const addresses = rankAddresses([entry('10.1.2.3'), entry('fd00::1', { family: 'ipv6', score: 115 })])
+ expect(linkHostOf('10.1.2.3', addresses)).toBe('10.1.2.3')
+ expect(linkHostOf('fd00::1', addresses)).toBe('fd00::1')
+ expect(linkHostOf('127.0.0.1', addresses)).toBe('127.0.0.1')
+ })
+
+ it('通配监听但没有任何可达地址时判为错误且不生成链接', () => {
+ const addresses = rankAddresses([entry('169.254.10.10', { scope: 'link-local', score: 30 })])
+ expect(linkHostOf('0.0.0.0', addresses)).toBeUndefined()
+ expect(addressProblemOf('0.0.0.0', addresses)).toBe('当前没有任何可用的对外地址,请重新选择网卡')
+ })
+
+ it('选定地址消失时给出重新选网卡的提示', () => {
+ const addresses = rankAddresses([entry('10.1.2.3')])
+ expect(addressProblemOf('10.1.2.4', addresses)).toBe('选定地址 10.1.2.4 已不存在,请重新选择网卡')
+ expect(addressProblemOf('10.1.2.3', addresses)).toBeUndefined()
+ expect(addressProblemOf('127.0.0.1', addresses)).toBeUndefined()
+ })
+
+ it('选定 link-local 地址时判为错误且不生成链接', () => {
+ const addresses = rankAddresses([entry('169.254.10.10', { scope: 'link-local', score: 30 })])
+ expect(linkHostOf('169.254.10.10', addresses)).toBeUndefined()
+ expect(addressProblemOf('169.254.10.10', addresses)).toContain('link-local')
+ })
+})
+
+describe('buildLink / maskLinkOf', () => {
+ it('iPv4 链接带端口与 auth 参数', () => {
+ expect(buildLink('192.168.1.5', 3089, 'abc123')).toBe('http://192.168.1.5:3089/?auth=abc123')
+ })
+
+ it('iPv6 链接给地址加方括号', () => {
+ expect(buildLink('fd00::1', 3089, 'abc123')).toBe('http://[fd00::1]:3089/?auth=abc123')
+ })
+
+ it('token 缺失时链接不带 auth 参数', () => {
+ expect(buildLink('192.168.1.5', 3089, null)).toBe('http://192.168.1.5:3089/')
+ })
+
+ it('掩码链接保留主机与端口、隐藏 Token', () => {
+ expect(maskLinkOf('192.168.1.5', 3089, true)).toBe('http://192.168.1.5:3089/?auth=***')
+ expect(maskLinkOf('fd00::1', 3089, true)).toBe('http://[fd00::1]:3089/?auth=***')
+ expect(maskLinkOf('192.168.1.5', 3089, false)).toBe('http://192.168.1.5:3089/')
+ })
+})
+
+describe('patchAccessDocument', () => {
+ it('password: null 清除已设密码,字符串则写入新哈希', () => {
+ const document = { ...defaultAccessDocument(), auth: { enabled: true, password: { algo: 'pbkdf2-sha256' as const, salt: 's', iterations: 1, hash: 'h' }, token: null, scope: 'public_only' as const } }
+ expect(patchAccessDocument(document, { password: null }, []).auth.password).toBeNull()
+ const written = patchAccessDocument(document, { password: 'next-pass' }, []).auth.password
+ expect(written?.algo).toBe('pbkdf2-sha256')
+ expect(written?.hash).not.toBe('h')
+ })
+
+ it('缺省字段保持原值,password 为只写字段', () => {
+ const document = { ...defaultAccessDocument(), enabled: true, auth: { enabled: true, password: null, token: 'keep', scope: 'all' as const } }
+ const next = patchAccessDocument(document, { port: 4100 }, [entry('10.1.2.3')])
+ expect(next.enabled).toBe(true)
+ expect(next.listen).toEqual({ address: DEFAULT_ACCESS_ADDRESS, port: 4100 })
+ expect(next.auth).toEqual({ enabled: true, password: null, token: 'keep', scope: 'all' })
+ })
+
+ it('提交密码时只存哈希且可被校验通过', () => {
+ const next = patchAccessDocument(defaultAccessDocument(), { password: 'hunter2' }, [])
+ expect(next.auth.password?.algo).toBe('pbkdf2-sha256')
+ expect(next.auth.password?.hash).not.toContain('hunter2')
+ expect(verifyPassword('hunter2', next.auth.password)).toBe(true)
+ expect(verifyPassword('hunter3', next.auth.password)).toBe(false)
+ })
+
+ it('非法端口、作用域与开关类型一律抛错', () => {
+ expect(() => patchAccessDocument(defaultAccessDocument(), { port: 0 }, [])).toThrowError('invalid port')
+ expect(() => patchAccessDocument(defaultAccessDocument(), { port: 65536 }, [])).toThrowError('invalid port')
+ expect(() => patchAccessDocument(defaultAccessDocument(), { scope: 'lan_only' as never }, [])).toThrowError('invalid scope')
+ expect(() => patchAccessDocument(defaultAccessDocument(), { enabled: 'yes' as never }, [])).toThrowError('invalid enabled')
+ expect(() => patchAccessDocument(defaultAccessDocument(), { password: '' }, [])).toThrowError('invalid password')
+ })
+
+ it('地址必须是当前存在的网卡、通配或回环之一', () => {
+ const addresses = [entry('10.1.2.3')]
+ expect(isSelectableAddress('10.1.2.3', addresses)).toBe(true)
+ expect(isSelectableAddress('0.0.0.0', addresses)).toBe(true)
+ expect(isSelectableAddress('127.0.0.1', addresses)).toBe(true)
+ expect(isSelectableAddress('10.1.2.4', addresses)).toBe(false)
+ expect(() => patchAccessDocument(defaultAccessDocument(), { address: '10.1.2.4' }, addresses)).toThrowError('invalid address: 10.1.2.4')
+ })
+})
+
+describe('redactStatus', () => {
+ it('非回环只保留开关、监听、认证开关与 scope、凭据存在性、地址清单与掩码链接', () => {
+ const redacted = redactStatus(statusFixture())
+ expect(redacted.link).toBeUndefined()
+ expect(redacted.qr).toBeUndefined()
+ expect(redacted.localPort).toBeUndefined()
+ expect(redacted.auth).toEqual({ enabled: true, scope: 'public_only', hasPassword: true, hasToken: true })
+ expect(redacted.maskLink).toBe('http://192.168.1.5:3089/?auth=***')
+ expect(redacted.listen).toEqual({ address: '192.168.1.5', port: 3088 })
+ expect(redacted.port).toBe(3089)
+ expect(redacted.state).toBe('listening')
+ expect(redacted.addresses).toHaveLength(1)
+ })
+
+ it('脱敏结果序列化后不含 Token、二维码与本机明细', () => {
+ const text = JSON.stringify(redactStatus(statusFixture()))
+ expect(text).not.toContain('secret-token')
+ expect(text).not.toContain('tunnel-secret')
+ expect(text).not.toContain('data:image/png')
+ expect(text).not.toContain('localPort')
+ })
+
+ it('隧道段脱敏后保留配置与状态,但不含 Token、链接与二维码', () => {
+ expect(statusFixture().tunnel?.token).toBe('tunnel-secret')
+ const redacted = redactStatus(statusFixture()).tunnel
+ expect(redacted).toEqual({
+ enabled: true,
+ mode: 'quick',
+ hostname: 'x.trycloudflare.com',
+ state: 'running',
+ events: [{ seq: 1, ts: '2026-10-05T00:00:00.000Z', kind: 'process', line: 'cloudflared 已启动' }],
+ url: 'https://x.trycloudflare.com',
+ port: 3089,
+ })
+ })
+})
+
+describe('pairingLinksOf', () => {
+ it('局域网与隧道两个入口各自独立:只开隧道时也要给出短期公网链接', () => {
+ expect(pairingLinksOf({ code: 'AB12CD34', host: undefined, port: 0, tunnelUrl: 'https://x.trycloudflare.com' }))
+ .toEqual({ tunnelLink: 'https://x.trycloudflare.com/?auth=AB12CD34' })
+ expect(pairingLinksOf({ code: 'AB12CD34', host: '192.168.1.5', port: 3088, tunnelUrl: undefined }))
+ .toEqual({ link: 'http://192.168.1.5:3088/?auth=AB12CD34' })
+ expect(pairingLinksOf({ code: 'AB12CD34', host: '192.168.1.5', port: 3088, tunnelUrl: 'https://x.trycloudflare.com' }))
+ .toEqual({ link: 'http://192.168.1.5:3088/?auth=AB12CD34', tunnelLink: 'https://x.trycloudflare.com/?auth=AB12CD34' })
+ expect(pairingLinksOf({ code: 'AB12CD34', host: undefined, port: 0, tunnelUrl: undefined })).toEqual({})
+ })
+})
+
+describe('policyOf', () => {
+ it('把文档映射为网关认证快照', () => {
+ const document = { ...defaultAccessDocument(), auth: { enabled: true, password: null, token: 'tok', scope: 'all' as const } }
+ expect(policyOf(document, 'secret')).toEqual({ enabled: true, scope: 'all', password: null, linkToken: 'tok', sessionSecret: 'secret' })
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/host/service/access.utils.ts b/packages/dsh-tauri-remote/src/host/service/access.utils.ts
new file mode 100644
index 00000000..31376952
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/access.utils.ts
@@ -0,0 +1,430 @@
+import type { NetworkInterfaceInfo } from 'node:os'
+import type { RemoteAuthPolicy, RemoteAuthScope, RemotePasswordRecord, RemoteTunnelStatus } from '../types/index'
+import type { RemoteAccessAddress, RemoteAccessBody, RemoteAccessDocument, RemoteAccessParse, RemoteAccessStatus, RemoteAddressFamily, RemoteAddressScope } from './access.types'
+import { randomBytes } from 'node:crypto'
+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { networkInterfaces } from 'node:os'
+import { dirname } from 'pathe'
+import { accessDocumentPath } from '../config/runtime'
+import { hashPassword } from '../utils/auth'
+import { classifyPeer } from '../utils/source'
+
+export const ACCESS_DOCUMENT_VERSION = 1
+
+export const DEFAULT_ACCESS_ADDRESS = '127.0.0.1'
+
+export const DEFAULT_ACCESS_PORT = 3088
+
+const DOCUMENT_KEYS = new Set(['version', 'enabled', 'listen', 'auth', 'tunnel'])
+
+const LISTEN_KEYS = new Set(['address', 'port'])
+
+const AUTH_KEYS = new Set(['enabled', 'password', 'token', 'scope'])
+
+const TUNNEL_KEYS = new Set(['enabled', 'mode', 'token', 'hostname'])
+
+const SCOPES: readonly RemoteAuthScope[] = ['public_only', 'all']
+
+/** 容器 / 虚拟机 / 隧道类网卡降权:物理网卡优先(S4 §7)。 */
+const VIRTUAL_INTERFACE = /^(?:lo|docker|br-|veth|virbr|vmnet|vboxnet|tun|tap|utun|wg\d|zt|tailscale|ham|bridge|anpi|awdl|llw|ap\d|VirtualBox|Hyper-V)/i
+
+const PHYSICAL_SCORE = 100
+
+const VIRTUAL_SCORE = 30
+
+const PRIVATE_SCORE = 20
+
+const IPV4_SCORE = 5
+
+const MASK = '***'
+
+export function defaultAccessDocument(): RemoteAccessDocument {
+ return {
+ version: ACCESS_DOCUMENT_VERSION,
+ enabled: false,
+ listen: { address: DEFAULT_ACCESS_ADDRESS, port: DEFAULT_ACCESS_PORT },
+ auth: { enabled: false, password: null, token: null, scope: 'public_only' },
+ tunnel: { enabled: false, mode: 'quick', token: null, hostname: null },
+ }
+}
+
+/** 解析失败视为「未配置」:回落默认文档 + `corrupt` 标记,调用方据此保留文件并给出可读原因(S4 §5)。 */
+export function parseAccessDocument(text: string | undefined): RemoteAccessParse {
+ const document = defaultAccessDocument()
+ const warnings: string[] = []
+ if (text === undefined || text.trim() === '')
+ return { document, corrupt: false, warnings }
+ const raw = plainObjectOf(text)
+ if (raw === undefined)
+ return { document, corrupt: true, warnings: ['access.json 解析失败,已按未配置处理(文件保留待手工修复)'] }
+ for (const key of Object.keys(raw)) {
+ if (!DOCUMENT_KEYS.has(key))
+ warnings.push(`access.json 丢弃未知键 ${key}`)
+ }
+ readVersion(raw, document, warnings)
+ readKnown(raw, document, warnings)
+ return { document, corrupt: false, warnings }
+}
+
+export function serializeAccessDocument(document: RemoteAccessDocument): string {
+ return `${JSON.stringify(document, null, 2)}\n`
+}
+
+export function readAccessDocument(): RemoteAccessParse {
+ let text: string | undefined
+ try {
+ text = readFileSync(accessDocumentPath(), 'utf8')
+ }
+ catch {
+ text = undefined
+ }
+ return parseAccessDocument(text)
+}
+
+export function writeAccessDocument(document: RemoteAccessDocument): void {
+ const file = accessDocumentPath()
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
+ const temp = `${file}.${randomBytes(6).toString('hex')}.tmp`
+ try {
+ writeFileSync(temp, serializeAccessDocument(document), { mode: 0o600, flag: 'wx' })
+ renameSync(temp, file)
+ }
+ catch (error) {
+ rmSync(temp, { force: true })
+ throw error
+ }
+}
+
+export function patchAccessDocument(document: RemoteAccessDocument, body: RemoteAccessBody, addresses: RemoteAccessAddress[]): RemoteAccessDocument {
+ const next: RemoteAccessDocument = {
+ version: ACCESS_DOCUMENT_VERSION,
+ enabled: document.enabled,
+ listen: { ...document.listen },
+ auth: { ...document.auth },
+ tunnel: document.tunnel,
+ }
+ if (body.enabled !== undefined) {
+ if (typeof body.enabled !== 'boolean')
+ throw new TypeError('invalid enabled')
+ next.enabled = body.enabled
+ }
+ if (body.address !== undefined) {
+ if (typeof body.address !== 'string' || !isSelectableAddress(body.address, addresses))
+ throw new TypeError(`invalid address: ${String(body.address)}`)
+ next.listen.address = body.address
+ }
+ if (body.port !== undefined) {
+ if (typeof body.port !== 'number' || !Number.isInteger(body.port) || body.port < 1 || body.port > 65535)
+ throw new TypeError('invalid port')
+ next.listen.port = body.port
+ }
+ if (body.authEnabled !== undefined) {
+ if (typeof body.authEnabled !== 'boolean')
+ throw new TypeError('invalid authEnabled')
+ next.auth.enabled = body.authEnabled
+ }
+ if (body.scope !== undefined) {
+ if (!isScope(body.scope))
+ throw new TypeError('invalid scope')
+ next.auth.scope = body.scope
+ }
+ if (body.password === null) {
+ next.auth.password = null
+ }
+ else if (body.password !== undefined) {
+ if (typeof body.password !== 'string' || body.password === '')
+ throw new TypeError('invalid password')
+ next.auth.password = hashPassword(body.password)
+ }
+ return next
+}
+
+export function isSelectableAddress(address: string, addresses: RemoteAccessAddress[]): boolean {
+ if (isWildcardListen(address) || isLoopbackListen(address))
+ return true
+ return addresses.some(entry => entry.address === address)
+}
+
+export function policyOf(document: RemoteAccessDocument, sessionSecret: string): RemoteAuthPolicy {
+ return {
+ enabled: document.auth.enabled,
+ scope: document.auth.scope,
+ password: document.auth.password,
+ linkToken: document.auth.token,
+ sessionSecret,
+ }
+}
+
+export function enumerateAddresses(interfaces: NodeJS.Dict<NetworkInterfaceInfo[]> = networkInterfaces()): RemoteAccessAddress[] {
+ const entries: RemoteAccessAddress[] = []
+ for (const [name, list] of Object.entries(interfaces)) {
+ for (const info of list ?? []) {
+ if (info.internal)
+ continue
+ const family: RemoteAddressFamily = info.family === 'IPv6' ? 'ipv6' : 'ipv4'
+ entries.push({
+ address: info.address,
+ family,
+ interface: name,
+ scope: addressScopeOf(info.address),
+ score: addressScoreOf(name, info.address),
+ recommended: false,
+ })
+ }
+ }
+ return rankAddresses(entries)
+}
+
+export function rankAddresses(entries: RemoteAccessAddress[]): RemoteAccessAddress[] {
+ const ranked = [...entries].sort((left, right) => right.score - left.score || left.address.localeCompare(right.address))
+ const top = ranked.find(entry => isReachableAddress(entry.address))
+ return ranked.map(entry => ({ ...entry, recommended: top !== undefined && entry.address === top.address }))
+}
+
+/** 对外可达地址:排除回环、link-local、带 zone id 的地址,以及 `0.0.0.0` 与 `::` 本身(S4 §7)。 */
+export function isReachableAddress(address: string): boolean {
+ if (address === '' || address.includes('%') || isWildcardListen(address))
+ return false
+ return !isLoopbackListen(address) && !isLinkLocalAddress(address)
+}
+
+export function isWildcardListen(address: string): boolean {
+ return address === '0.0.0.0' || address === '::'
+}
+
+export function isLoopbackListen(address: string): boolean {
+ return address === '::1' || classifyPeer(address) === 'loopback'
+}
+
+export function linkHostOf(listen: string, addresses: RemoteAccessAddress[]): string | undefined {
+ if (isWildcardListen(listen))
+ return addresses.find(entry => entry.recommended)?.address
+ if (isLoopbackListen(listen))
+ return listen
+ return isReachableAddress(listen) ? listen : undefined
+}
+
+export function addressProblemOf(listen: string, addresses: RemoteAccessAddress[]): string | undefined {
+ if (isWildcardListen(listen))
+ return addresses.some(entry => entry.recommended) ? undefined : '当前没有任何可用的对外地址,请重新选择网卡'
+ if (isLoopbackListen(listen))
+ return undefined
+ if (!addresses.some(entry => entry.address === listen))
+ return `选定地址 ${listen} 已不存在,请重新选择网卡`
+ return isReachableAddress(listen) ? undefined : `选定地址 ${listen} 不可用于对外访问(link-local 或带 zone id),请重新选择网卡`
+}
+
+export function buildLink(host: string, port: number, token: string | null): string {
+ const authority = host.includes(':') ? `[${host}]` : host
+ return `http://${authority}:${port}/${token === null || token === '' ? '' : `?auth=${encodeURIComponent(token)}`}`
+}
+
+export function maskLinkOf(host: string, port: number, hasToken: boolean): string {
+ return buildLink(host, port, hasToken ? MASK : null)
+}
+
+/** 公网隧道的访问链接:隧道地址本身已是 https,Token 语义与局域网链接一致。 */
+export function buildTunnelLink(url: string, token: string | null): string {
+ return token === null || token === '' ? `${url}/` : `${url}/?auth=${encodeURIComponent(token)}`
+}
+
+/**
+ * 同一临时配对码可以落成两个入口:局域网(监听中才有真实端口)与公网隧道(隧道就绪才有地址)。
+ * 任一入口可用就给出对应链接,两者互不依赖——只开隧道、不开局域网时也必须能分享短期链接。
+ */
+export function pairingLinksOf(input: { code: string, host: string | undefined, port: number, tunnelUrl: string | undefined }): { link?: string, tunnelLink?: string } {
+ const link = input.host === undefined || input.port === 0 ? undefined : buildLink(input.host, input.port, input.code)
+ const tunnelLink = input.tunnelUrl === undefined ? undefined : buildTunnelLink(input.tunnelUrl, input.code)
+ return { ...link === undefined ? {} : { link }, ...tunnelLink === undefined ? {} : { tunnelLink } }
+}
+
+/** 脱敏(S4 §6):只保留开关、监听、认证开关/scope 与凭据存在性、地址清单、掩码链接与状态,绝不带 Token / 二维码 / 本机明细。 */
+export function redactStatus(status: RemoteAccessStatus): RemoteAccessStatus {
+ return {
+ version: status.version,
+ enabled: status.enabled,
+ state: status.state,
+ listening: status.listening,
+ listen: status.listen,
+ port: status.port,
+ auth: {
+ enabled: status.auth.enabled,
+ scope: status.auth.scope,
+ ...status.auth.hasPassword === undefined ? {} : { hasPassword: status.auth.hasPassword },
+ ...status.auth.hasToken === undefined ? {} : { hasToken: status.auth.hasToken },
+ },
+ addresses: status.addresses,
+ events: status.events,
+ ...status.recommended === undefined ? {} : { recommended: status.recommended },
+ ...status.maskLink === undefined ? {} : { maskLink: status.maskLink },
+ ...status.linkSource === undefined ? {} : { linkSource: status.linkSource },
+ ...status.tunnel === undefined ? {} : { tunnel: redactTunnel(status.tunnel) },
+ ...status.error === undefined ? {} : { error: status.error },
+ ...status.warnings === undefined ? {} : { warnings: status.warnings },
+ }
+}
+
+/** 隧道脱敏:保留配置与运行期状态,去掉凭据与只属于完整分支的链接/二维码。 */
+export function redactTunnel(status: RemoteTunnelStatus): RemoteTunnelStatus {
+ const { token, link, qr, ...rest } = status
+ return rest
+}
+
+// --- internal ---
+function readVersion(raw: Record<string, unknown>, document: RemoteAccessDocument, warnings: string[]): void {
+ const version = raw.version
+ if (typeof version === 'number' && Number.isInteger(version) && version > 0) {
+ document.version = version
+ return
+ }
+ if (version !== undefined)
+ warnings.push('access.json 的 version 非法,已回落 1')
+}
+
+function readKnown(raw: Record<string, unknown>, document: RemoteAccessDocument, warnings: string[]): void {
+ if (typeof raw.enabled === 'boolean')
+ document.enabled = raw.enabled
+ else if (raw.enabled !== undefined)
+ warnings.push('access.json 的 enabled 非法,已回落 false')
+ readListen(raw.listen, document, warnings)
+ readAuth(raw.auth, document, warnings)
+ readTunnel(raw.tunnel, document, warnings)
+}
+
+function readListen(value: unknown, document: RemoteAccessDocument, warnings: string[]): void {
+ if (value === undefined)
+ return
+ if (!isPlainObject(value)) {
+ warnings.push('access.json 的 listen 非法,已回落默认')
+ return
+ }
+ for (const key of Object.keys(value)) {
+ if (!LISTEN_KEYS.has(key))
+ warnings.push(`access.json 丢弃未知键 listen.${key}`)
+ }
+ const address = value.address
+ if (typeof address === 'string' && address !== '')
+ document.listen.address = address
+ else if (address !== undefined)
+ warnings.push('access.json 的 listen.address 非法,已回落 127.0.0.1')
+ const port = value.port
+ if (typeof port === 'number' && Number.isInteger(port) && port >= 1 && port <= 65535)
+ document.listen.port = port
+ else if (port !== undefined)
+ warnings.push('access.json 的 listen.port 非法,已回落 3088')
+}
+
+function readAuth(value: unknown, document: RemoteAccessDocument, warnings: string[]): void {
+ if (value === undefined)
+ return
+ if (!isPlainObject(value)) {
+ warnings.push('access.json 的 auth 非法,已回落默认')
+ return
+ }
+ for (const key of Object.keys(value)) {
+ if (!AUTH_KEYS.has(key))
+ warnings.push(`access.json 丢弃未知键 auth.${key}`)
+ }
+ if (typeof value.enabled === 'boolean')
+ document.auth.enabled = value.enabled
+ else if (value.enabled !== undefined)
+ warnings.push('access.json 的 auth.enabled 非法,已回落 false')
+ if (isScope(value.scope))
+ document.auth.scope = value.scope
+ else if (value.scope !== undefined)
+ warnings.push('access.json 的 auth.scope 非法,已回落 public_only')
+ if (value.password !== null && value.password !== undefined) {
+ const record = passwordRecordOf(value.password)
+ if (record === undefined)
+ warnings.push('access.json 的 auth.password 非法,已丢弃')
+ else
+ document.auth.password = record
+ }
+ if (typeof value.token === 'string' && value.token !== '')
+ document.auth.token = value.token
+ else if (value.token !== undefined && value.token !== null)
+ warnings.push('access.json 的 auth.token 非法,已丢弃')
+}
+
+function readTunnel(value: unknown, document: RemoteAccessDocument, warnings: string[]): void {
+ if (value === undefined)
+ return
+ if (!isPlainObject(value)) {
+ warnings.push('access.json 的 tunnel 非法,已回落默认')
+ return
+ }
+ for (const key of Object.keys(value)) {
+ if (!TUNNEL_KEYS.has(key))
+ warnings.push(`access.json 丢弃未知键 tunnel.${key}`)
+ }
+ if (typeof value.enabled === 'boolean')
+ document.tunnel.enabled = value.enabled
+ else if (value.enabled !== undefined)
+ warnings.push('access.json 的 tunnel.enabled 非法,已回落 false')
+ if (value.mode === 'quick' || value.mode === 'token')
+ document.tunnel.mode = value.mode
+ else if (value.mode !== undefined)
+ warnings.push('access.json 的 tunnel.mode 非法,已回落 quick')
+ if (typeof value.token === 'string' && value.token !== '')
+ document.tunnel.token = value.token
+ else if (value.token !== undefined && value.token !== null)
+ warnings.push('access.json 的 tunnel.token 非法,已丢弃')
+ if (typeof value.hostname === 'string' && value.hostname !== '')
+ document.tunnel.hostname = value.hostname
+ else if (value.hostname !== undefined && value.hostname !== null)
+ warnings.push('access.json 的 tunnel.hostname 非法,已丢弃')
+}
+
+/** 只校验形态、不校验可用性:损坏的记录必须原样保留,才能让 S2 的「认证存储损坏」引导生效(S2 §11)。 */
+function passwordRecordOf(value: unknown): RemotePasswordRecord | undefined {
+ if (!isPlainObject(value))
+ return undefined
+ const iterations = value.iterations
+ if (value.algo !== 'pbkdf2-sha256' || typeof value.salt !== 'string' || typeof value.hash !== 'string')
+ return undefined
+ if (typeof iterations !== 'number' || !Number.isInteger(iterations) || iterations <= 0)
+ return undefined
+ return { algo: 'pbkdf2-sha256', salt: value.salt, iterations, hash: value.hash }
+}
+
+function plainObjectOf(text: string): Record<string, unknown> | undefined {
+ let raw: unknown
+ try {
+ raw = JSON.parse(text)
+ }
+ catch {
+ return undefined
+ }
+ return isPlainObject(raw) ? raw : undefined
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function isScope(value: unknown): value is RemoteAuthScope {
+ return (SCOPES as readonly unknown[]).includes(value)
+}
+
+function addressScopeOf(address: string): RemoteAddressScope {
+ const peer = classifyPeer(address)
+ if (peer === 'loopback')
+ return 'loopback'
+ if (isLinkLocalAddress(address))
+ return 'link-local'
+ return peer === 'private' ? 'private' : 'public'
+}
+
+function addressScoreOf(name: string, address: string): number {
+ let score = VIRTUAL_INTERFACE.test(name) ? VIRTUAL_SCORE : PHYSICAL_SCORE
+ if (classifyPeer(address) === 'private')
+ score += PRIVATE_SCORE
+ if (!address.includes(':'))
+ score += IPV4_SCORE
+ return score
+}
+
+function isLinkLocalAddress(address: string): boolean {
+ const host = address.split('%')[0] ?? ''
+ return host.includes(':') ? /^fe[89ab]/i.test(host) : host.startsWith('169.254.')
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.arm64-dryrun.test.ts b/packages/dsh-tauri-remote/src/host/service/bootstrap.arm64-dryrun.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/bootstrap.arm64-dryrun.test.ts
rename to packages/dsh-tauri-remote/src/host/service/bootstrap.arm64-dryrun.test.ts
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts b/packages/dsh-tauri-remote/src/host/service/bootstrap.e2e.test.ts
similarity index 93%
rename from packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts
rename to packages/dsh-tauri-remote/src/host/service/bootstrap.e2e.test.ts
index 1d7caeb6..f7b81654 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts
+++ b/packages/dsh-tauri-remote/src/host/service/bootstrap.e2e.test.ts
@@ -1,17 +1,17 @@
/* eslint-disable no-console -- the run's console output IS the recorded evidence */
-import type { MachineProfile, SshLink, SshSession } from '../types/index'
-import type { SshTransportOptions } from './transport.types'
+import type { MachineProfile, RemoteLink, RemoteSession } from '../types/index'
+import type { RemoteTransportOptions } from './transport.types'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'pathe'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
-import { resetRuntime, setHostConfig, setKnownHostsPath, setMachineDeps } from '../config/runtime'
+import { clearHostRuntime, setHostConfig, setKnownHostsPath, setMachineDeps } from '../config/runtime'
import { MachineId } from '../types/index'
import { EMPTY_ALLOWLIST } from '../utils/allowlist'
import { resolveSshAuth } from '../utils/ssh-config'
import { events } from './events'
import { machine } from './machine'
-import { transport } from './transport'
+import { sshTransport } from './transport.ssh'
const HOME_DIR = process.env.HOME ?? ''
const SSH_DIR = join(HOME_DIR, '.ssh')
@@ -89,24 +89,24 @@ EOF
describe.skipIf(HOST === undefined)('bootstrap E2E (real linux x64 remote)', () => {
const roots: string[] = []
- const options: SshTransportOptions = {
+ const options: RemoteTransportOptions = {
readyTimeoutMs: E2E_CONFIG.connectTimeoutMs,
resolveProfile: credentialsOf,
keepaliveIntervalMs: E2E_CONFIG.keepaliveIntervalMs,
keepaliveCountMax: E2E_CONFIG.keepaliveCountMax,
}
- async function openRaw(): Promise<SshSession> {
- return await transport.connect(profile, () => true, options)
+ async function openRaw(): Promise<RemoteSession> {
+ return await sshTransport.connect(profile, () => true, options)
}
beforeAll(() => {
const known = mkdtempSync(join(tmpdir(), 'dsh-ssh-e2e-'))
roots.push(known)
- resetRuntime()
+ clearHostRuntime()
setHostConfig({ ...E2E_CONFIG, sshDir: SSH_DIR })
setKnownHostsPath(join(known, 'known-hosts.json'))
- setMachineDeps({ transport, emitStatus: () => {}, localAllowlist: () => EMPTY_ALLOWLIST })
+ setMachineDeps({ transport: { resolve: () => sshTransport }, emitStatus: () => {}, localAllowlist: () => EMPTY_ALLOWLIST })
machine.refreshProfiles(new Map([[profile.id, profile]]))
})
@@ -136,7 +136,7 @@ describe.skipIf(HOST === undefined)('bootstrap E2E (real linux x64 remote)', ()
expect(wiped.stdout).toContain('wiped')
const startedAt = Date.now()
- let link: SshLink
+ let link: RemoteLink
try {
link = await machine.connect(profile.id)
}
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts b/packages/dsh-tauri-remote/src/host/service/bootstrap.test.ts
similarity index 99%
rename from packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts
rename to packages/dsh-tauri-remote/src/host/service/bootstrap.test.ts
index ee45c2ec..8e4f1958 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts
+++ b/packages/dsh-tauri-remote/src/host/service/bootstrap.test.ts
@@ -1,4 +1,4 @@
-import type { MachineProfile, SshExecOptions, SshExecResult, SshSession } from '../types/index'
+import type { MachineProfile, RemoteExecOptions, RemoteExecResult, RemoteSession } from '../types/index'
import type { RemoteInstallPlan } from './bootstrap.types'
import { Buffer } from 'node:buffer'
import { execFile } from 'node:child_process'
@@ -102,17 +102,17 @@ function stubGithub(): void {
})
}
-class FakeSession implements SshSession {
+class FakeSession implements RemoteSession {
commands: string[] = []
- constructor(private readonly responder: (command: string, index: number) => SshExecResult) {}
+ constructor(private readonly responder: (command: string, index: number) => RemoteExecResult) {}
- exec(command: string, _options?: SshExecOptions): Promise<SshExecResult> {
+ exec(command: string, _options?: RemoteExecOptions): Promise<RemoteExecResult> {
this.commands.push(command)
return Promise.resolve(this.responder(command, this.commands.length - 1))
}
- openTunnel(): Promise<never> {
+ stream(): Promise<never> {
throw new Error('unused')
}
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts b/packages/dsh-tauri-remote/src/host/service/bootstrap.ts
similarity index 85%
rename from packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
rename to packages/dsh-tauri-remote/src/host/service/bootstrap.ts
index 8963f58b..7187f408 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
+++ b/packages/dsh-tauri-remote/src/host/service/bootstrap.ts
@@ -1,4 +1,4 @@
-import type { MachineProfile, SshSession } from '../types/index'
+import type { MachineProfile, RemoteSession } from '../types/index'
import type { BootstrapHooks, RemoteInstallPlan } from './bootstrap.types'
import { defineService } from 'dsh-tauri'
import { hostConfig } from '../config/runtime'
@@ -6,7 +6,7 @@ import { ensureRemoteInstance, runInstallScript } from './bootstrap.utils'
export const bootstrap = defineService({
async provision(
- session: SshSession,
+ session: RemoteSession,
profile: MachineProfile,
hooks: BootstrapHooks = {},
): Promise<string> {
@@ -14,7 +14,7 @@ export const bootstrap = defineService({
},
async install(
- session: SshSession,
+ session: RemoteSession,
plan: RemoteInstallPlan,
hooks: BootstrapHooks = {},
failureLine = 'bootstrap 失败',
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.types.ts b/packages/dsh-tauri-remote/src/host/service/bootstrap.types.ts
similarity index 74%
rename from packages/dsh-tauri-ssh/src/host/service/bootstrap.types.ts
rename to packages/dsh-tauri-remote/src/host/service/bootstrap.types.ts
index 03bc1dc5..d4da032d 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.types.ts
+++ b/packages/dsh-tauri-remote/src/host/service/bootstrap.types.ts
@@ -1,8 +1,8 @@
-import type { SshMachineStage, SshMachineTerminal, SshProgress } from '../types/index'
+import type { RemoteMachineStage, RemoteMachineTerminal, RemoteProgress } from '../types/index'
import type { RemoteArch, RemoteAssetMatrix, RemoteOs } from '../utils/assets'
export interface BootstrapLogLine {
- stage: SshMachineStage
+ stage: RemoteMachineStage
line: string
}
@@ -41,6 +41,6 @@ export interface EnvCredentials {
}
export interface BootstrapHooks {
- onProgress?: (progress: SshProgress) => void
- onEvent?: (stage: SshMachineStage, line: string, options?: { terminal?: SshMachineTerminal, reason?: string }) => void
+ onProgress?: (progress: RemoteProgress) => void
+ onEvent?: (stage: RemoteMachineStage, line: string, options?: { terminal?: RemoteMachineTerminal, reason?: string }) => void
}
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.utils.ts b/packages/dsh-tauri-remote/src/host/service/bootstrap.utils.ts
similarity index 97%
rename from packages/dsh-tauri-ssh/src/host/service/bootstrap.utils.ts
rename to packages/dsh-tauri-remote/src/host/service/bootstrap.utils.ts
index 2c310c03..186c5f19 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.utils.ts
+++ b/packages/dsh-tauri-remote/src/host/service/bootstrap.utils.ts
@@ -1,5 +1,5 @@
import type { Config } from '../config/schema'
-import type { MachineProfile, SshMachineStage, SshSession } from '../types/index'
+import type { MachineProfile, RemoteMachineStage, RemoteSession } from '../types/index'
import type { BootstrapHooks, BootstrapLogLine, EnvCredentials, RemoteInstallPlan } from './bootstrap.types'
import { Buffer } from 'node:buffer'
import { readFileSync } from 'node:fs'
@@ -20,7 +20,7 @@ const DSH_NPM_ENTRY = 'lib/bin.js'
const PNPM_ENTRY = 'bin/pnpm.cjs'
-const BOOTSTRAP_STAGES: Record<SshMachineStage, true> = {
+const BOOTSTRAP_STAGES: Record<RemoteMachineStage, true> = {
probe: true,
download: true,
verify: true,
@@ -32,7 +32,7 @@ const BOOTSTRAP_STAGES: Record<SshMachineStage, true> = {
reconnect: true,
}
-function isBootstrapStage(value: string): value is SshMachineStage {
+function isBootstrapStage(value: string): value is RemoteMachineStage {
return (BOOTSTRAP_STAGES as Record<string, true | undefined>)[value] === true
}
@@ -523,7 +523,7 @@ export function describeExecFailure(code: number | null, stderr: string): string
}
export async function ensureRemoteInstance(
- session: SshSession,
+ session: RemoteSession,
profile: MachineProfile,
config: Config,
hooks: BootstrapHooks = {},
@@ -587,7 +587,7 @@ export async function ensureRemoteInstance(
)
}
-async function judgeReadiness(session: SshSession, profile: MachineProfile, config: Config): Promise<string | undefined> {
+async function judgeReadiness(session: RemoteSession, profile: MachineProfile, config: Config): Promise<string | undefined> {
const root = await session.exec(rootProbeCommand(profile.remotePort, config.healthCheckTimeoutMs))
if (root.code !== 0)
return undefined
@@ -614,7 +614,7 @@ export function legacyProbeCommand(remotePort: number, timeoutMs: number): strin
].join('; ')
}
-async function legacyRootVerdict(session: SshSession, profile: MachineProfile, config: Config): Promise<string> {
+async function legacyRootVerdict(session: RemoteSession, profile: MachineProfile, config: Config): Promise<string> {
const probe = await session.exec(legacyProbeCommand(profile.remotePort, config.healthCheckTimeoutMs))
if (probe.stdout.includes(REMOTE_PROBE_NO_DOWNLOADER))
return `no downloader (${REMOTE_PROBE_NO_DOWNLOADER}: 远端缺少 curl 与 wget,无法探测就绪状态)`
@@ -622,7 +622,7 @@ async function legacyRootVerdict(session: SshSession, profile: MachineProfile, c
}
export async function runInstallScript(
- session: SshSession,
+ session: RemoteSession,
plan: RemoteInstallPlan,
installTimeoutMs: number,
hooks: BootstrapHooks,
@@ -673,7 +673,7 @@ function failBootstrap(onEvent: BootstrapHooks['onEvent'], reason: string, line
throw new Error(reason)
}
-async function logTail(session: SshSession): Promise<string> {
+async function logTail(session: RemoteSession): Promise<string> {
try {
const result = await session.exec(logTailCommand())
const tail = result.stdout.trim()
diff --git a/packages/dsh-tauri-ssh/src/host/service/events.test.ts b/packages/dsh-tauri-remote/src/host/service/events.test.ts
similarity index 97%
rename from packages/dsh-tauri-ssh/src/host/service/events.test.ts
rename to packages/dsh-tauri-remote/src/host/service/events.test.ts
index 23b12a1f..c7ff17c6 100644
--- a/packages/dsh-tauri-ssh/src/host/service/events.test.ts
+++ b/packages/dsh-tauri-remote/src/host/service/events.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it } from 'vitest'
import { EVENT_RING_CAPACITY } from '../config/constants'
-import { resetRuntime, setEventCapacity } from '../config/runtime'
+import { clearHostRuntime, setEventCapacity } from '../config/runtime'
import { MachineId } from '../types/index'
import { events } from './events'
@@ -8,7 +8,7 @@ const m1 = MachineId('m1')
const m2 = MachineId('m2')
beforeEach(() => {
- resetRuntime()
+ clearHostRuntime()
setEventCapacity(EVENT_RING_CAPACITY)
})
diff --git a/packages/dsh-tauri-ssh/src/host/service/events.ts b/packages/dsh-tauri-remote/src/host/service/events.ts
similarity index 74%
rename from packages/dsh-tauri-ssh/src/host/service/events.ts
rename to packages/dsh-tauri-remote/src/host/service/events.ts
index c00c082a..88c4cd47 100644
--- a/packages/dsh-tauri-ssh/src/host/service/events.ts
+++ b/packages/dsh-tauri-remote/src/host/service/events.ts
@@ -1,12 +1,12 @@
-import type { MachineId, SshMachineEvent, SshMachineEventsPage, SshMachineStage, SshMachineTerminal } from '../types/index'
+import type { MachineId, RemoteMachineEvent, RemoteMachineEventsPage, RemoteMachineStage, RemoteMachineTerminal } from '../types/index'
import { defineService } from 'dsh-tauri'
import { eventBuffers, eventRingCapacity } from '../config/runtime'
export const events = defineService({
- append(machineId: MachineId, stage: SshMachineStage, line: string, options: { terminal?: SshMachineTerminal, reason?: string } = {}): SshMachineEvent {
+ append(machineId: MachineId, stage: RemoteMachineStage, line: string, options: { terminal?: RemoteMachineTerminal, reason?: string } = {}): RemoteMachineEvent {
const buffer = ensureBuffer(machineId)
buffer.seq += 1
- const event: SshMachineEvent = {
+ const event: RemoteMachineEvent = {
seq: buffer.seq,
ts: new Date().toISOString(),
machineId,
@@ -22,7 +22,7 @@ export const events = defineService({
return event
},
- since(machineId: MachineId, sinceSeq?: number): SshMachineEventsPage {
+ since(machineId: MachineId, sinceSeq?: number): RemoteMachineEventsPage {
const buffer = eventBuffers.get(machineId)
if (buffer === undefined)
return { events: [], nextSeq: 1 }
@@ -38,7 +38,7 @@ export const events = defineService({
},
})
-function ensureBuffer(machineId: MachineId): { seq: number, events: SshMachineEvent[] } {
+function ensureBuffer(machineId: MachineId): { seq: number, events: RemoteMachineEvent[] } {
let buffer = eventBuffers.get(machineId)
if (buffer === undefined) {
buffer = { seq: 0, events: [] }
diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.auth.ts b/packages/dsh-tauri-remote/src/host/service/gateway.auth.ts
new file mode 100644
index 00000000..149c0d60
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/gateway.auth.ts
@@ -0,0 +1,92 @@
+import type { ComponentType } from 'react'
+import type { Rolldown } from 'tsdown'
+import { Buffer } from 'node:buffer'
+import { readFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { dirname, join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { createElement } from 'react'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { Rolldown as bundler } from 'tsdown'
+
+const require = createRequire(import.meta.url)
+const buildRequire = createRequire(require.resolve('tsdown'))
+const { transform } = buildRequire('lightningcss') as {
+ transform: (options: { filename: string, code: Buffer, cssModules: boolean, minify: boolean }) => { code: Buffer, exports: Record<string, { name: string }> }
+}
+
+let html: Promise<string> | undefined
+
+export function gatewayAuthHtml(): Promise<string> {
+ return html ??= renderGatewayAuthHtml()
+}
+
+async function renderGatewayAuthHtml(): Promise<string> {
+ const atomsEntry = require.resolve('@deepseek-ai/dsh-client-ui-primitives')
+ const atomsRequire = createRequire(atomsEntry)
+ const styles: string[] = []
+ const bundle = await bundler.rolldown({
+ input: 'gateway-auth',
+ platform: 'node',
+ transform: { define: { window: 'undefined' } },
+ treeshake: {
+ moduleSideEffects: false,
+ propertyReadSideEffects: false,
+ manualPureFunctions: ['memo', 'forwardRef', 'createContext', 'createCssVariablesTheme', 'createJavaScriptRegexEngine', 'createMathFlow', 'createSnapshotStore', 'Object.freeze', 'setTimeout'],
+ },
+ plugins: [{
+ name: 'gateway-auth',
+ resolveId(id) {
+ if (id === 'gateway-auth')
+ return '\0gateway-auth'
+ if (id === '@deepseek-ai/dsh-client-ui-primitives')
+ return atomsEntry
+ if (/^[^./\0]/.test(id)) {
+ let resolved: string
+ try {
+ resolved = pathToFileURL(atomsRequire.resolve(id)).href
+ }
+ catch {
+ resolved = id
+ }
+ return { id: resolved, external: true, moduleSideEffects: false }
+ }
+ },
+ load(id) {
+ if (id === '\0gateway-auth')
+ return 'export { FishLogo, Input, Button } from \'@deepseek-ai/dsh-client-ui-primitives\''
+ if (!id.endsWith('.css'))
+ return
+ if (!/(?:Button|Input)\.module\.css$/.test(id))
+ return { code: 'export default {}', moduleType: 'js', moduleSideEffects: false }
+ const result = transform({ filename: id, code: readFileSync(id), cssModules: true, minify: true })
+ styles.push(result.code.toString())
+ const classes = Object.fromEntries(Object.entries(result.exports).map(([key, value]) => [key, value.name]))
+ return { code: `export default ${JSON.stringify(classes)}`, moduleType: 'js', moduleSideEffects: false }
+ },
+ }],
+ })
+ let code: string
+ try {
+ const { output } = await bundle.generate({ format: 'esm', inlineDynamicImports: true })
+ code = (output[0] as Rolldown.OutputChunk).code
+ }
+ finally {
+ await bundle.close()
+ }
+ const { FishLogo, Input, Button } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`) as Record<'FishLogo' | 'Input' | 'Button', ComponentType<Record<string, unknown>>>
+ const themeSource = readFileSync(join(dirname(require.resolve('@deepseek-ai/dsh-client-ui-theme')), 'client.js'), 'utf8')
+ const theme = ['base', 'design_platform', 'focus'].map((name) => {
+ const literal = themeSource.match(new RegExp(`var ${name}_css_default = ("(?:[^"\\\\]|\\\\.)*");`))?.[1]
+ if (literal === undefined)
+ throw new Error(`Gateway auth theme is missing ${name} CSS`)
+ return JSON.parse(literal) as string
+ }).join('')
+ const dark = [...theme.matchAll(/body\[data-ds-dark-theme\]\{[^}]+\}/g)].map(match => match[0].replace('body[data-ds-dark-theme]', 'body')).join('')
+ if (dark === '')
+ throw new Error('Gateway auth theme is missing dark tokens')
+ const css = `${theme}@media(prefers-color-scheme:dark){${dark}}${styles.join('')}
+*{box-sizing:border-box}html{color-scheme:light dark}body{margin:0;min-height:100svh;display:grid;place-items:center;padding:24px;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-family:var(--dsw-font-family)}main{width:min(100%,360px);text-align:center}main>svg{color:var(--dsw-alias-state-business-primary)}h1{font-size:24px;line-height:32px;font-weight:600;margin:20px 0 32px}form{display:grid;gap:16px}label{font-size:14px;line-height:22px;text-align:left}form>span{height:44px}input{font:inherit}form>button{height:44px;width:100%}[role=alert]{color:var(--dsw-alias-state-error-primary);font-size:14px;line-height:22px;margin:0 0 16px}`
+ const body = renderToStaticMarkup(createElement('main', null, createElement(FishLogo, { size: 64 }), createElement('h1', null, 'DeepSeek Harness'), '__GATEWAY_AUTH_MESSAGE__', createElement('form', { method: 'post' }, createElement('label', { htmlFor: 'password' }, '请输入配对码'), createElement(Input, { id: 'password', name: 'password', type: 'password', autoComplete: 'current-password', autoFocus: true, required: true }), createElement(Button, { type: 'submit', variant: 'primary' }, '连接'))))
+ return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>DeepSeek Harness</title><style>${css}</style></head><body>${body}</body></html>`
+}
diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.test.ts b/packages/dsh-tauri-remote/src/host/service/gateway.test.ts
new file mode 100644
index 00000000..aedcbfcc
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/gateway.test.ts
@@ -0,0 +1,2416 @@
+import type { IncomingHttpHeaders, IncomingMessage } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import type { Duplex } from 'node:stream'
+import type { RemoteAuthPolicy, RemoteGatewayEntryKind, RemoteGatewayEvent, RemoteGatewayStartOptions, RemotePasswordRecord } from '../types/index'
+import { Buffer } from 'node:buffer'
+import { createHash } from 'node:crypto'
+import { once } from 'node:events'
+import { createServer, request as httpRequest } from 'node:http'
+import { connect, createServer as createNetServer } from 'node:net'
+import { networkInterfaces } from 'node:os'
+import * as zlib from 'node:zlib'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { GATEWAY_SESSION_HEADER, GATEWAY_SOURCE_HEADER } from '../config/constants'
+import { ensureSourceSession } from '../config/runtime'
+import { createLinkToken, hashPassword, signSession, verifySession } from '../utils/auth'
+import { classifySource } from '../utils/source'
+import { gateway } from './gateway'
+import { consumePairingCode, PAIRING_TTL_MS, pairingCodeOf, resetPairingCode } from './pairing'
+
+const SESSION = ensureSourceSession()
+
+const MIN_BYTES = 1024
+
+interface Coded {
+ status: number
+ headers: IncomingHttpHeaders
+ body: Buffer
+}
+
+interface Streamed {
+ status: number
+ headers: IncomingHttpHeaders
+ stream: IncomingMessage
+}
+
+interface Upgraded {
+ status: number
+ headers: IncomingHttpHeaders
+ socket: Duplex
+}
+
+interface UpstreamCall {
+ method: string
+ url: string
+ headers: IncomingHttpHeaders
+}
+
+interface FakeUpstream {
+ port: number
+ origin: string
+ calls: UpstreamCall[]
+ upgrades: UpstreamCall[]
+ mintCount: number
+ token: string
+ mintUrlFor: (authority: string) => Promise<string>
+ restart: () => void
+ releaseEvents: () => void
+ waitForCall: (url: string) => Promise<void>
+ waitForStall: () => Promise<void>
+ close: () => Promise<void>
+}
+
+function loopbackHost(host: string): boolean {
+ const bare = host.startsWith('[') ? host.slice(1, -1) : host
+ return bare === '127.0.0.1' || bare === '::1' || bare === 'localhost'
+}
+
+function cookieOf(headers: IncomingHttpHeaders): string | undefined {
+ const value = headers.cookie
+ return Array.isArray(value) ? value.join('; ') : value
+}
+
+function cookieValueOf(headers: IncomingHttpHeaders, name: string): string | undefined {
+ return (cookieOf(headers) ?? '')
+ .split(';')
+ .map(pair => pair.trim())
+ .find(pair => pair.startsWith(`${name}=`))
+ ?.slice(name.length + 1)
+}
+
+function localAuthorityOf(headers: IncomingHttpHeaders): string | undefined {
+ const host = headers.host
+ if (typeof host !== 'string' || host === '')
+ return undefined
+ try {
+ return new URL(`http://${host}`).host
+ }
+ catch {
+ return undefined
+ }
+}
+
+/** 与 DSH 真实实现同构的会话 cookie 名:`dsh-auth-` + base64url(sha256(authority))。 */
+function cookieNameOf(authority: string): string {
+ return `dsh-auth-${createHash('sha256').update(authority).digest('base64url')}`
+}
+
+function grantedCookieOf(headers: IncomingHttpHeaders): string | undefined {
+ const authority = localAuthorityOf(headers)
+ return authority === undefined ? undefined : cookieValueOf(headers, cookieNameOf(authority))
+}
+
+/** 最小 DSH 等价上游:Host/Origin/Sec-Fetch-Site fence + authority 绑定 cookie + 静态资源 + /api + SSE + Upgrade。 */
+function startFakeUpstream(): Promise<FakeUpstream> {
+ const granted = new Map<string, Set<string>>()
+ const waiters = new Map<string, Array<() => void>>()
+ const state = {
+ token: 'launch-token-1',
+ sequence: 0,
+ mintCount: 0,
+ calls: [] as UpstreamCall[],
+ upgrades: [] as UpstreamCall[],
+ release: (): void => {},
+ stalled: (): void => {},
+ }
+ const fenced = (headers: IncomingHttpHeaders, pathname: string): boolean => {
+ const authority = localAuthorityOf(headers)
+ if (authority === undefined || !loopbackHost(new URL(`http://${authority}`).hostname))
+ return false
+ if (pathname.startsWith('/api/') && headers['sec-fetch-site'] === 'cross-site')
+ return false
+ const origin = headers.origin
+ if (typeof origin !== 'string')
+ return true
+ try {
+ return new URL(origin).host === authority
+ }
+ catch {
+ return false
+ }
+ }
+ const sessionGranted = (headers: IncomingHttpHeaders): boolean => {
+ const authority = localAuthorityOf(headers)
+ const value = grantedCookieOf(headers)
+ return authority !== undefined && value !== undefined && (granted.get(authority)?.has(value) ?? false)
+ }
+ const sockets = new Set<Duplex>()
+ const server = createServer((request, response) => {
+ const url = new URL(request.url ?? '/', 'http://dsh.invalid')
+ state.calls.push({ method: request.method ?? '', url: request.url ?? '', headers: request.headers })
+ for (const release of waiters.get(url.pathname) ?? [])
+ release()
+ waiters.delete(url.pathname)
+ if (!fenced(request.headers, url.pathname)) {
+ response.writeHead(403, { 'content-type': 'text/plain' })
+ response.end('fence')
+ return
+ }
+ if (request.method === 'GET' && url.pathname === '/') {
+ const tokens = url.searchParams.getAll('token')
+ if (tokens.length === 1) {
+ if (tokens[0] !== state.token) {
+ response.writeHead(401, { 'content-type': 'application/json' })
+ response.end('{"error":"bad token"}')
+ return
+ }
+ state.mintCount += 1
+ state.sequence += 1
+ const value = `mint-${state.sequence}`
+ const authority = localAuthorityOf(request.headers) ?? ''
+ const name = cookieNameOf(authority)
+ const values = granted.get(authority) ?? new Set<string>()
+ values.add(value)
+ granted.set(authority, values)
+ response.writeHead(303, { 'location': './', 'set-cookie': `${name}=${value}; Max-Age=2592000; Path=/; HttpOnly; SameSite=Strict` })
+ response.end()
+ return
+ }
+ }
+ if (!sessionGranted(request.headers)) {
+ response.writeHead(401, { 'content-type': 'application/json' })
+ response.end('{"error":"unauthorized"}')
+ return
+ }
+ if (url.pathname === '/') {
+ const html = `<html><body>${'x'.repeat(3000)}</body></html>`
+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': String(Buffer.byteLength(html)) })
+ response.end(html)
+ return
+ }
+ if (url.pathname === '/api/ping') {
+ response.writeHead(200, { 'content-type': 'application/json' })
+ response.end('{"ok":true}')
+ return
+ }
+ if (url.pathname === '/api/echo') {
+ const chunks: Buffer[] = []
+ request.on('data', (chunk: Buffer) => chunks.push(chunk))
+ request.on('end', () => {
+ const body = JSON.stringify({ received: Buffer.concat(chunks).length })
+ response.writeHead(200, { 'content-type': 'application/json', 'content-length': String(Buffer.byteLength(body)) })
+ response.end(body)
+ })
+ return
+ }
+ if (url.pathname === '/big') {
+ const text = 'b'.repeat(MIN_BYTES * 4)
+ response.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'content-length': String(text.length) })
+ response.end(text)
+ return
+ }
+ if (url.pathname === '/chunked') {
+ response.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
+ response.write('c'.repeat(MIN_BYTES))
+ response.end('d'.repeat(MIN_BYTES))
+ return
+ }
+ if (url.pathname === '/small') {
+ const text = 'tiny'
+ response.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'content-length': String(text.length) })
+ response.end(text)
+ return
+ }
+ if (url.pathname === '/chunked-small') {
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
+ response.end('{"ok":true}')
+ return
+ }
+ if (url.pathname === '/image') {
+ const png = Buffer.alloc(MIN_BYTES * 2, 7)
+ response.writeHead(200, { 'content-type': 'image/png', 'content-length': String(png.length) })
+ response.end(png)
+ return
+ }
+ if (url.pathname === '/gz') {
+ const body = zlib.gzipSync(Buffer.from('g'.repeat(MIN_BYTES * 2)))
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'content-encoding': 'gzip', 'content-length': String(body.length) })
+ response.end(body)
+ return
+ }
+ if (url.pathname === '/sse') {
+ response.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' })
+ response.write('data: one\n\n')
+ state.release = () => {
+ response.write('data: two\n\n')
+ response.end()
+ }
+ return
+ }
+ if (url.pathname === '/redirect') {
+ response.writeHead(302, { location: `http://127.0.0.1:${(server.address() as AddressInfo).port}/` })
+ response.end()
+ return
+ }
+ if (url.pathname === '/upstream-cookie') {
+ const body = 'with-cookie'
+ response.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'content-length': String(body.length), 'set-cookie': 'dsh_upstream_credential=leaked; Path=/; HttpOnly' })
+ response.end(body)
+ return
+ }
+ if (url.pathname === '/abort-big' || url.pathname === '/abort-small') {
+ const size = url.pathname === '/abort-big' ? MIN_BYTES * 4 : 300
+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
+ response.write('x'.repeat(size))
+ setTimeout(() => {
+ request.socket.destroy()
+ }, 20)
+ return
+ }
+ if (url.pathname === '/gz-abort') {
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'content-encoding': 'gzip' })
+ response.write(zlib.gzipSync(Buffer.from('g'.repeat(MIN_BYTES * 4))))
+ setTimeout(() => {
+ request.socket.destroy()
+ }, 20)
+ return
+ }
+ if (url.pathname === '/gz-sse-abort') {
+ response.writeHead(200, { 'content-type': 'text/event-stream', 'content-encoding': 'gzip' })
+ response.write(zlib.gzipSync(Buffer.from('data: one\n\n')))
+ setTimeout(() => {
+ request.socket.destroy()
+ }, 20)
+ return
+ }
+ if (url.pathname === '/stall') {
+ state.stalled()
+ return
+ }
+ response.writeHead(404, { 'content-type': 'text/plain' })
+ response.end('not found')
+ })
+ server.on('upgrade', (request, socket) => {
+ state.upgrades.push({ method: request.method ?? '', url: request.url ?? '', headers: request.headers })
+ if ((request.url ?? '') === '/stall') {
+ state.stalled()
+ return
+ }
+ /** 恒定用过期凭据拒绝,使升级路径总是走到 401 重铸分支(重铸窗口的活性用例需要它)。 */
+ if ((request.url ?? '') === '/retry') {
+ socket.write('HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\n\r\n')
+ socket.destroy()
+ return
+ }
+ if (!fenced(request.headers, request.url ?? '/') || !sessionGranted(request.headers)) {
+ socket.write('HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\n\r\n')
+ socket.destroy()
+ return
+ }
+ if ((request.url ?? '') === '/upgrade-403' || (request.url ?? '') === '/upgrade-404') {
+ const status = request.url === '/upgrade-403' ? '403 Forbidden' : '404 Not Found'
+ const body = 'denied by upstream'
+ socket.write((request.url ?? '') === '/upgrade-403'
+ ? `HTTP/1.1 ${status}\r\ncontent-type: text/plain\r\ncontent-length: ${Buffer.byteLength(body)}\r\n\r\n${body}`
+ : `HTTP/1.1 ${status}\r\ncontent-type: text/plain\r\ntransfer-encoding: chunked\r\n\r\n${Buffer.byteLength(body).toString(16)}\r\n${body}\r\n0\r\n\r\n`)
+ socket.end()
+ return
+ }
+ socket.write('HTTP/1.1 101 Switching Protocols\r\nupgrade: websocket\r\nconnection: Upgrade\r\n\r\n')
+ socket.write('echo:hello')
+ socket.on('data', (chunk: Buffer) => socket.write(Buffer.concat([Buffer.from('echo:'), chunk])))
+ })
+ server.on('connection', (socket) => {
+ sockets.add(socket)
+ socket.on('close', () => sockets.delete(socket))
+ })
+ return new Promise((resolve) => {
+ server.listen(0, '127.0.0.1', () => {
+ const port = (server.address() as AddressInfo).port
+ resolve({
+ port,
+ origin: `http://127.0.0.1:${port}`,
+ calls: state.calls,
+ upgrades: state.upgrades,
+ get mintCount() {
+ return state.mintCount
+ },
+ get token() {
+ return state.token
+ },
+ set token(next: string) {
+ state.token = next
+ },
+ mintUrlFor: async (authority: string) => `http://${authority}/?token=${state.token}`,
+ restart: () => {
+ state.sequence += 1
+ state.token = `launch-token-${state.sequence + 1}`
+ granted.clear()
+ },
+ releaseEvents: () => state.release(),
+ waitForCall: (path: string) => new Promise<void>((resolve) => {
+ const pending = waiters.get(path) ?? []
+ pending.push(resolve)
+ waiters.set(path, pending)
+ }),
+ waitForStall: () => new Promise<void>((resolve) => {
+ state.stalled = resolve
+ }),
+ close: () => new Promise<void>((done) => {
+ for (const socket of sockets)
+ socket.destroy()
+ server.close(() => done())
+ }),
+ } as FakeUpstream)
+ })
+ })
+}
+
+interface RawUpstream {
+ port: number
+ origin: string
+ requests: string[]
+ waitForRequests: (count: number) => Promise<string[]>
+ close: () => Promise<void>
+}
+
+/** 逐块切出上游连接上的一个完整请求:正文只按声明的方式定位,绝不把裸尾部字节当成正文。 */
+function splitMessage(buffer: Buffer): { head: string, body: Buffer, rest: Buffer } | undefined {
+ const at = buffer.indexOf('\r\n\r\n')
+ if (at === -1)
+ return undefined
+ const head = buffer.subarray(0, at).toString('latin1')
+ const start = at + 4
+ if (/^transfer-encoding:\s*chunked$/im.test(head)) {
+ let cursor = start
+ while (cursor < buffer.length) {
+ const lineEnd = buffer.indexOf('\r\n', cursor)
+ if (lineEnd === -1)
+ return undefined
+ const size = Number.parseInt(buffer.subarray(cursor, lineEnd).toString('latin1'), 16)
+ if (!Number.isInteger(size))
+ return { head, body: buffer.subarray(start), rest: Buffer.alloc(0) }
+ if (size === 0) {
+ const end = lineEnd + 2 + 2
+ if (buffer.length < end)
+ return undefined
+ return { head, body: buffer.subarray(start, end), rest: buffer.subarray(end) }
+ }
+ const next = lineEnd + 2 + size + 2
+ if (buffer.length < next)
+ return undefined
+ cursor = next
+ }
+ return undefined
+ }
+ const declared = /^content-length:\s*(\d+)$/im.exec(head)
+ const length = declared === null ? 0 : Number(declared[1])
+ if (buffer.length < start + length)
+ return undefined
+ return { head, body: buffer.subarray(start, start + length), rest: buffer.subarray(start + length) }
+}
+
+/** 裸 TCP 上游:按原始字节记录网关写出的每个请求,铸造型请求就地回 303 + set-cookie。 */
+function rawUpstream(): Promise<RawUpstream> {
+ const requests: string[] = []
+ const waiters: Array<() => void> = []
+ const sockets = new Set<Duplex>()
+ const server = createNetServer((socket) => {
+ sockets.add(socket)
+ socket.on('close', () => sockets.delete(socket))
+ let buffer: Buffer<ArrayBufferLike> = Buffer.alloc(0)
+ const drain = (): void => {
+ for (;;) {
+ const parsed = splitMessage(buffer)
+ if (parsed === undefined)
+ return
+ buffer = parsed.rest
+ requests.push(`${parsed.head}\r\n\r\n${parsed.body.toString('latin1')}`)
+ for (const release of waiters.splice(0))
+ release()
+ if (parsed.head.startsWith('GET /?token='))
+ socket.write('HTTP/1.1 303 See Other\r\nset-cookie: minted=1; Path=/\r\ncontent-length: 0\r\n\r\n')
+ else
+ socket.write('HTTP/1.1 200 OK\r\ncontent-type: text/plain; charset=utf-8\r\ncontent-length: 2\r\n\r\nok')
+ }
+ }
+ socket.on('data', (chunk: Buffer) => {
+ buffer = Buffer.concat([buffer, chunk])
+ drain()
+ })
+ socket.on('error', () => {})
+ })
+ return new Promise((resolve) => {
+ server.listen(0, '127.0.0.1', () => {
+ const port = (server.address() as AddressInfo).port
+ resolve({
+ port,
+ origin: `http://127.0.0.1:${port}`,
+ requests,
+ waitForRequests: async (count: number) => {
+ while (requests.length < count) {
+ await new Promise<void>((done) => {
+ waiters.push(done)
+ setTimeout(done, 3000)
+ })
+ }
+ return requests
+ },
+ close: () => new Promise<void>((done) => {
+ for (const socket of sockets)
+ socket.destroy()
+ server.close(() => done())
+ }),
+ })
+ })
+ })
+}
+
+function headOf(raw: string): string {
+ const at = raw.indexOf('\r\n\r\n')
+ return at === -1 ? raw : raw.slice(0, at)
+}
+
+function bodyOf(raw: string): string {
+ const at = raw.indexOf('\r\n\r\n')
+ return at === -1 ? '' : raw.slice(at + 4)
+}
+
+/** 按分块编码解出正文:解出内容与原文一致,才说明这串字节在上游连接上仍是一段正文。 */
+function decodeChunked(body: string): string {
+ let cursor = 0
+ let decoded = ''
+ while (cursor < body.length) {
+ const lineEnd = body.indexOf('\r\n', cursor)
+ if (lineEnd === -1)
+ break
+ const size = Number.parseInt(body.slice(cursor, lineEnd), 16)
+ if (!Number.isInteger(size) || size === 0)
+ break
+ decoded += Buffer.from(body.slice(lineEnd + 2, lineEnd + 2 + size), 'latin1').toString('latin1')
+ cursor = lineEnd + 2 + size + 2
+ }
+ return decoded
+}
+
+function call(port: number, path: string, options: { method?: string, headers?: IncomingHttpHeaders, body?: Buffer | string } = {}): Promise<Coded> {
+ return new Promise((resolve, reject) => {
+ const request = httpRequest({
+ host: '127.0.0.1',
+ port,
+ path,
+ method: options.method ?? 'GET',
+ headers: { connection: 'close', ...options.headers },
+ }, (response) => {
+ const chunks: Buffer[] = []
+ response.on('data', (chunk: Buffer) => chunks.push(chunk))
+ response.on('end', () => resolve({ status: response.statusCode ?? 0, headers: response.headers, body: Buffer.concat(chunks) }))
+ })
+ request.on('error', reject)
+ request.end(options.body)
+ })
+}
+
+function streamed(port: number, path: string, headers: IncomingHttpHeaders = {}): Promise<Streamed> {
+ return new Promise((resolve, reject) => {
+ const request = httpRequest({ host: '127.0.0.1', port, path, headers }, (response) => {
+ resolve({ status: response.statusCode ?? 0, headers: response.headers, stream: response })
+ })
+ request.on('error', reject)
+ request.end()
+ })
+}
+
+/** 裸 socket 回读网关写出的原始升级响应字节:非 101 的分帧只有在这一层才可判。 */
+function rawUpgrade(port: number, path: string, headers: IncomingHttpHeaders): Promise<{ head: string, body: string }> {
+ return new Promise((resolve, reject) => {
+ const socket = connect(port, '127.0.0.1', () => {
+ const lines = [`GET ${path} HTTP/1.1`, `host: 127.0.0.1:${port}`, 'connection: Upgrade', 'upgrade: websocket', ...Object.entries(headers).map(([name, value]) => `${name}: ${Array.isArray(value) ? value.join(', ') : String(value)}`)]
+ socket.write(`${lines.join('\r\n')}\r\n\r\n`)
+ })
+ const chunks: Buffer[] = []
+ socket.on('data', (chunk: Buffer) => chunks.push(chunk))
+ socket.on('error', reject)
+ socket.on('close', () => {
+ const text = Buffer.concat(chunks).toString('utf8')
+ const at = text.indexOf('\r\n\r\n')
+ resolve({ head: at === -1 ? text : text.slice(0, at), body: at === -1 ? '' : text.slice(at + 4) })
+ })
+ setTimeout(() => socket.destroy(), 2000)
+ })
+}
+
+/** 半关闭的升级连接不会触发 'close':客户端断开必须等 'end' 或 'close' 两条都观测。 */
+function disconnect(socket: Duplex): Promise<void> {
+ return new Promise((resolve) => {
+ socket.on('close', () => resolve())
+ socket.on('end', () => resolve())
+ socket.destroy()
+ })
+}
+
+/** 发起升级握手但不等应答:上游是 /stall,网关只会把请求转出去。 */
+function stalledUpgrade(port: number, headers: IncomingHttpHeaders, path = '/stall'): Promise<Duplex> {
+ return new Promise((resolve, reject) => {
+ const socket = connect(port, '127.0.0.1', () => {
+ const lines = [`GET ${path} HTTP/1.1`, `host: 127.0.0.1:${port}`, 'connection: Upgrade', 'upgrade: websocket', ...Object.entries(headers).map(([name, value]) => `${name}: ${Array.isArray(value) ? value.join(', ') : String(value)}`)]
+ socket.write(`${lines.join('\r\n')}\r\n\r\n`)
+ resolve(socket)
+ })
+ socket.on('error', reject)
+ })
+}
+
+/** 假时钟下推进时间不会推进真实 I/O,这里让事件循环转光再回读客户端已经收到的字节。 */
+async function settledTextOf(pending: Promise<string>): Promise<string> {
+ let text = ''
+ void pending.then((value) => {
+ text = value
+ })
+ await new Promise(resolve => setImmediate(resolve))
+ return text
+}
+
+async function turns(count: number): Promise<void> {
+ for (let index = 0; index < count; index++)
+ await new Promise(resolve => setImmediate(resolve))
+}
+
+/** 假时钟下推进时间不会推进真实 I/O:等待真实轮次而不是 waitFor(后者按真实时间轮询,会在假时钟下失去意义)。 */
+async function until(condition: () => boolean, turnsPerAttempt = 4, attempts = 250): Promise<void> {
+ for (let attempt = 0; attempt < attempts; attempt++) {
+ if (condition())
+ return
+ await turns(turnsPerAttempt)
+ }
+ throw new Error('等待条件超时')
+}
+
+function upgraded(port: number, path: string, headers: IncomingHttpHeaders): Promise<Upgraded> {
+ return new Promise((resolve, reject) => {
+ const request = httpRequest({ host: '127.0.0.1', port, path, headers: { connection: 'Upgrade', upgrade: 'websocket', ...headers } })
+ request.on('upgrade', (response, socket, head) => {
+ if (head.length > 0)
+ socket.unshift(head)
+ resolve({ status: response.statusCode ?? 0, headers: response.headers, socket })
+ })
+ request.on('response', (response) => {
+ response.resume()
+ response.on('end', () => reject(new Error(`升级被拒:${response.statusCode ?? 0}`)))
+ })
+ request.on('error', reject)
+ request.end()
+ })
+}
+
+interface Observed {
+ kind: 'end' | 'aborted' | 'error' | 'no-response'
+ status: number
+ bodyLength: number
+}
+
+/** 观测一次响应如何终止:正常结束 / 中途断开 / 无响应,用于断言「上游断流」后的客户端所见。 */
+function observed(port: number, path: string, headers: IncomingHttpHeaders, timeoutMs = 2000): Promise<Observed> {
+ return new Promise((resolve) => {
+ let settled = false
+ let length = 0
+ const finish = (kind: Observed['kind'], status = 0): void => {
+ if (settled)
+ return
+ settled = true
+ resolve({ kind, status, bodyLength: length })
+ }
+ const request = httpRequest({ host: '127.0.0.1', port, path, headers: { connection: 'close', ...headers }, agent: false }, (response) => {
+ const status = response.statusCode ?? 0
+ response.on('data', (chunk: Buffer) => {
+ length += chunk.length
+ })
+ response.on('end', () => finish('end', status))
+ response.on('aborted', () => finish('aborted', status))
+ response.on('error', () => finish('error', status))
+ })
+ request.on('error', () => finish('error'))
+ setTimeout(finish, timeoutMs, 'no-response')
+ request.end()
+ })
+}
+
+function decodeReply(reply: Coded): string {
+ const coding = reply.headers['content-encoding']
+ if (coding === 'zstd')
+ return zlib.zstdDecompressSync(reply.body).toString('utf8')
+ if (coding === 'gzip')
+ return zlib.gunzipSync(reply.body).toString('utf8')
+ return reply.body.toString('utf8')
+}
+
+function markerHeaders(source: string, extra: IncomingHttpHeaders = {}): IncomingHttpHeaders {
+ return { [GATEWAY_SOURCE_HEADER]: source, [GATEWAY_SESSION_HEADER]: SESSION, ...extra }
+}
+
+/** cloudflared 把 Host 改写成回环 authority,但浏览器发出的 Fetch 元数据原样转发。 */
+function tunnelHeaders(cookie: string, extra: IncomingHttpHeaders = {}): IncomingHttpHeaders {
+ return { cookie, 'sec-fetch-site': 'same-origin', ...extra }
+}
+
+function navigation(): IncomingHttpHeaders {
+ return { accept: 'text/html,application/xhtml+xml' }
+}
+
+function policyOf(overrides: Partial<RemoteAuthPolicy> = {}): RemoteAuthPolicy {
+ return { enabled: true, scope: 'public_only', password: hashPassword('s3cret', 1000), linkToken: null, sessionSecret: 'session-secret', ...overrides }
+}
+
+async function startEntry(kind: RemoteGatewayEntryKind, upstream: FakeUpstream, options: Partial<RemoteGatewayStartOptions> = {}) {
+ return await gateway.start({ id: 'entry', kind, upstream: upstream.origin, port: 0, ...options })
+}
+
+async function freePort(): Promise<{ port: number, release: () => Promise<void> }> {
+ const server = createNetServer()
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
+ const port = (server.address() as AddressInfo).port
+ return { port, release: () => new Promise<void>((done) => {
+ server.close(() => done())
+ }) }
+}
+
+let upstream: FakeUpstream
+
+beforeEach(async () => {
+ upstream = await startFakeUpstream()
+})
+
+afterEach(async () => {
+ await gateway.dispose()
+ await upstream.close()
+ resetPairingCode()
+ vi.restoreAllMocks()
+})
+
+describe('gateway 转发与 DSH 原生 cookie 注入', () => {
+ it('自动铸造并注入上游会话 cookie,浏览器侧无需任何凭据', async () => {
+ const status = await startEntry('outbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const reply = await call(status.port, '/api/ping')
+ expect(reply.status).toBe(200)
+ expect(reply.body.toString()).toBe('{"ok":true}')
+ expect(upstream.calls).toHaveLength(2)
+ expect(upstream.calls[0]?.url).toBe('/?token=launch-token-1')
+ expect(grantedCookieOf(upstream.calls[1]?.headers ?? {})).toMatch(/^mint-/)
+ })
+
+ it('按上游 authority 缓存铸造结果,命中即直接注入', async () => {
+ const status = await startEntry('outbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ await call(status.port, '/api/ping')
+ await call(status.port, '/api/ping')
+ await call(status.port, '/api/ping')
+ expect(upstream.mintCount).toBe(1)
+ })
+
+ it('冷缓存下的并发请求共用一次铸造', async () => {
+ const status = await startEntry('outbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const replies = await Promise.all([1, 2, 3, 4, 5].map(async () => await call(status.port, '/api/ping')))
+ expect(replies.map(reply => reply.status)).toEqual([200, 200, 200, 200, 200])
+ expect(upstream.mintCount).toBe(1)
+ })
+
+ it('入口停止后同一 authority 的铸造结果失效,重新开启时重新铸造', async () => {
+ await withReservedPort(async (preferred) => {
+ const first = await gateway.start({ id: 'entry', kind: 'outbound', upstream: upstream.origin, port: preferred, tokenProvider: upstream.mintUrlFor })
+ expect(first.port).toBe(preferred)
+ const warm = await call(preferred, '/api/echo', { method: 'POST', body: 'x' })
+ expect(warm.status).toBe(200)
+ expect(upstream.mintCount).toBe(1)
+
+ upstream.restart()
+ await gateway.stop('entry')
+ const provider = vi.fn(upstream.mintUrlFor)
+ const second = await gateway.start({ id: 'entry', kind: 'outbound', upstream: upstream.origin, port: preferred, tokenProvider: provider })
+ expect(second.port).toBe(preferred)
+
+ const replayable = await call(preferred, '/api/echo', { method: 'POST', body: 'x' })
+ expect(replayable.status).toBe(200)
+ expect(provider).toHaveBeenCalledTimes(1)
+ expect(upstream.mintCount).toBe(2)
+ })
+ })
+
+ it('入站与隧道腿剥离上游 set-cookie 但照常下发网关切身签发的会话 cookie,出站腿保留上游 set-cookie', async () => {
+ const inbound = await gateway.start({ id: 'inbound', kind: 'inbound', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor })
+ const forwarded = await call(inbound.port, '/upstream-cookie', { headers: markerHeaders('private') })
+ expect(forwarded.status).toBe(200)
+ expect(forwarded.headers['set-cookie']).toBeUndefined()
+
+ const tunnel = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ linkToken: 'link-token' }) })
+ const session = signSession('session-secret', Date.now()).value
+ const visitor = await call(tunnel.port, '/upstream-cookie', { headers: tunnelHeaders(`dsh_remote_session=${session}`) })
+ expect(visitor.status).toBe(200)
+ expect(JSON.stringify(visitor.headers['set-cookie'] ?? '')).not.toContain('dsh_upstream_credential')
+ const login = await call(tunnel.port, '/', { headers: tunnelHeaders('', { accept: 'text/html' }) })
+ expect(login.status).toBe(401)
+ expect(JSON.stringify(login.headers['set-cookie'] ?? '')).not.toContain('dsh_upstream_credential')
+ const granted = await call(tunnel.port, '/?auth=link-token', { headers: { 'sec-fetch-site': 'same-origin' } })
+ expect(granted.status).toBe(302)
+ expect(JSON.stringify(granted.headers['set-cookie'])).toContain('dsh_remote_session=')
+
+ const outbound = await gateway.start({ id: 'outbound', kind: 'outbound', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor })
+ const local = await call(outbound.port, '/upstream-cookie')
+ expect(JSON.stringify(local.headers['set-cookie'])).toContain('dsh_upstream_credential=leaked')
+ })
+
+ it('转发时把 Host 与 Origin 改写为浏览器所见的网关回环 authority', async () => {
+ const status = await startEntry('outbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ await call(status.port, '/api/ping', { headers: { host: `127.0.0.1:${status.port}`, origin: `http://127.0.0.1:${status.port}` } })
+ const forwarded = upstream.calls.at(-1)
+ expect(forwarded?.headers.host).toBe(`127.0.0.1:${status.port}`)
+ expect(forwarded?.headers.origin).toBe(`http://127.0.0.1:${status.port}`)
+ })
+
+ it('保留浏览器自带的其它 cookie,只覆盖同名的那一枚', async () => {
+ const status = await startEntry('outbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ await call(status.port, '/api/ping', { headers: { cookie: 'theme=dark' } })
+ expect(cookieOf(upstream.calls.at(-1)?.headers ?? {})).toMatch(new RegExp(`^theme=dark; ${cookieNameOf(`127.0.0.1:${status.port}`)}=mint-`))
+ })
+
+ it.each([false, true])('出站 HTTP 写入非授权标记,远端回环不能取得本机来源或秘密(伪回环=%s)', async (forged) => {
+ const status = await startEntry('outbound', upstream, {
+ tokenProvider: upstream.mintUrlFor,
+ host: '127.0.0.1',
+ })
+ const reply = await call(status.port, '/api/ping', {
+ headers: { 'accept-encoding': 'zstd, gzip', ...(forged ? markerHeaders('loopback') : {}) },
+ })
+ expect(reply.status).toBe(200)
+ const forwarded = upstream.calls.at(-1)?.headers ?? {}
+ expect(forwarded['accept-encoding']).toBe('identity')
+ expect(forwarded[GATEWAY_SOURCE_HEADER]).toBe('public')
+ expect(forwarded[GATEWAY_SESSION_HEADER]).toBe('outbound')
+ expect(JSON.stringify(forwarded)).not.toContain(SESSION)
+ for (const remoteSession of ['', 'remote-session', 'outbound']) {
+ expect(classifySource(forwarded, '127.0.0.1', remoteSession)).toBe('public')
+ expect(classifySource(forwarded, '::1', remoteSession)).toBe('public')
+ expect(classifySource(forwarded, '::ffff:127.0.0.1', remoteSession)).toBe('public')
+ }
+ })
+
+ it('token provider 失败时透传上游 401、记录可读事件且不缓存失败结果', async () => {
+ const events: RemoteGatewayEvent[] = []
+ const unsubscribe = gateway.subscribe(event => events.push(event))
+ let calls = 0
+ const status = await startEntry('outbound', upstream, {
+ tokenProvider: async () => {
+ calls += 1
+ return undefined
+ },
+ })
+ const first = await call(status.port, '/api/ping')
+ const second = await call(status.port, '/api/ping')
+ unsubscribe()
+ expect(first.status).toBe(401)
+ expect(second.status).toBe(401)
+ expect(calls).toBe(2)
+ expect(events.filter(event => event.kind === 'cookie').map(event => event.line))
+ .toEqual([1, 2].map(() => `DSH 原生 cookie 铸造失败(token 不可用),已透传上游响应(127.0.0.1:${status.port})`))
+ expect(JSON.stringify(events)).not.toContain(SESSION)
+ })
+
+ it('token provider 抛错时透传上游响应并记录一条可读事件', async () => {
+ const events: RemoteGatewayEvent[] = []
+ const unsubscribe = gateway.subscribe(event => events.push(event))
+ const status = await startEntry('outbound', upstream, {
+ tokenProvider: async () => {
+ throw new Error('远端实例尚未就绪')
+ },
+ })
+ const reply = await call(status.port, '/api/ping')
+ unsubscribe()
+ expect(reply.status).toBe(401)
+ expect(events.some(event => event.kind === 'cookie' && event.line.includes('远端实例尚未就绪'))).toBe(true)
+ expect(JSON.stringify(events)).not.toContain(SESSION)
+ })
+
+ it('上游重启后失效的可重放请求在首次 401 时重铸 cookie 并重试成功', async () => {
+ const provider = vi.fn(upstream.mintUrlFor)
+ const status = await startEntry('outbound', upstream, { tokenProvider: provider })
+ expect((await call(status.port, '/api/ping')).status).toBe(200)
+ upstream.restart()
+ const reply = await call(status.port, '/api/ping')
+ expect(reply.status).toBe(200)
+ expect(reply.body.toString()).toBe('{"ok":true}')
+ expect(upstream.mintCount).toBe(2)
+ expect(provider).toHaveBeenCalledTimes(2)
+ })
+
+ it('失效的凭据重铸失败时透传 401,且不再发第二次上游请求', async () => {
+ let failing = false
+ const provider = vi.fn(async (authority: string) => failing ? undefined : await upstream.mintUrlFor(authority))
+ const status = await startEntry('outbound', upstream, { tokenProvider: provider })
+ expect((await call(status.port, '/api/ping')).status).toBe(200)
+ expect(provider).toHaveBeenCalledTimes(1)
+ failing = true
+ upstream.restart()
+ const before = upstream.calls.length
+ const reply = await call(status.port, '/api/echo', { method: 'POST', headers: { 'content-length': '0' } })
+ expect(reply.status).toBe(401)
+ expect(provider).toHaveBeenCalledTimes(2)
+ const attempts = upstream.calls.slice(before)
+ expect(attempts).toHaveLength(1)
+ expect(attempts.map(entry => entry.method)).toEqual(['POST'])
+ expect(grantedCookieOf(attempts[0]?.headers ?? {})).toMatch(/^mint-/)
+ })
+
+ it('已发出请求体的请求遇到 401 时直接透传,不重试', async () => {
+ const status = await startEntry('outbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ await call(status.port, '/api/ping')
+ const mints = upstream.mintCount
+ upstream.restart()
+ const reply = await call(status.port, '/api/echo', { method: 'POST', headers: { 'content-type': 'text/plain' }, body: 'payload' })
+ expect(reply.status).toBe(401)
+ expect(upstream.mintCount).toBe(mints)
+ })
+
+ it('上游不可达时返回 502 与含上游地址的可读原因', async () => {
+ const dead = await freePort()
+ const port = dead.port
+ await dead.release()
+ const status = await gateway.start({ id: 'entry', kind: 'outbound', upstream: `http://127.0.0.1:${port}`, port: 0 })
+ const reply = await call(status.port, '/api/ping')
+ expect(reply.status).toBe(502)
+ expect(JSON.parse(reply.body.toString()).error).toContain(`http://127.0.0.1:${port}`)
+ })
+
+ it('上游迟迟不响应时按短超时返回 504', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ try {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const pending = call(status.port, '/stall')
+ await upstream.waitForCall('/stall')
+ vi.advanceTimersByTime(30_001)
+ const reply = await pending
+ expect(reply.status).toBe(504)
+ expect(JSON.parse(reply.body.toString()).error).toContain(`http://127.0.0.1:${upstream.port}`)
+ }
+ finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('流式转发大请求体,不整体缓冲', async () => {
+ const status = await startEntry('outbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const payload = Buffer.alloc(3 * 1024 * 1024, 3)
+ const reply = await call(status.port, '/api/echo', { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: payload })
+ expect(reply.status).toBe(200)
+ expect(JSON.parse(reply.body.toString())).toEqual({ received: payload.length })
+ })
+
+ it('原样透传指向回环地址的重定向', async () => {
+ const status = await startEntry('outbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const reply = await call(status.port, '/redirect')
+ expect(reply.status).toBe(302)
+ expect(reply.headers.location).toBe(`http://127.0.0.1:${upstream.port}/`)
+ })
+})
+
+describe('gateway 转发请求的正文分帧(裸上游字节断言)', () => {
+ it('转发带分块正文的读类请求时重新分块写出:已解码的正文绝不以第二个请求的形态落在上游连接上', async () => {
+ const raw = await rawUpstream()
+ const status = await gateway.start({ id: 'entry', kind: 'outbound', upstream: raw.origin, port: 0, tokenProvider: async authority => `http://${authority}/?token=launch-token-1` })
+ try {
+ const payload = 'GET /smuggled HTTP/1.1\r\nhost: 127.0.0.1:1\r\n\r\n'
+ const body = `5\r\nhello\r\n0\r\n\r\n${payload}`
+ const reply = await call(status.port, '/x', { method: 'GET', headers: { 'transfer-encoding': 'chunked' }, body })
+ expect(reply.status).toBe(200)
+ const forwarded = (await raw.waitForRequests(2)).at(-1) ?? ''
+ const head = headOf(forwarded)
+ const wire = bodyOf(forwarded)
+ expect(head.split('\r\n')[0]).toBe('GET /x HTTP/1.1')
+ expect(head.toLowerCase()).toContain('transfer-encoding: chunked')
+ expect(head.toLowerCase()).not.toContain('content-length')
+ expect(wire.endsWith('0\r\n\r\n')).toBe(true)
+ expect(decodeChunked(wire)).toBe(body)
+ expect(wire.startsWith('\r\nGET /smuggled')).toBe(false)
+ expect(wire.startsWith('GET /smuggled')).toBe(false)
+ }
+ finally {
+ await gateway.stop('entry')
+ await raw.close()
+ }
+ })
+
+ it('转发带分块正文的写类请求时同样按上游声明的分块写出,逐块字节可校验', async () => {
+ const raw = await rawUpstream()
+ const status = await gateway.start({ id: 'entry', kind: 'outbound', upstream: raw.origin, port: 0, tokenProvider: async authority => `http://${authority}/?token=launch-token-1` })
+ try {
+ const reply = await call(status.port, '/x', { method: 'POST', headers: { 'transfer-encoding': 'chunked', 'content-type': 'text/plain' }, body: 'hello' })
+ expect(reply.status).toBe(200)
+ const forwarded = (await raw.waitForRequests(2)).at(-1) ?? ''
+ expect(headOf(forwarded).toLowerCase()).toContain('transfer-encoding: chunked')
+ expect(bodyOf(forwarded)).toBe('5\r\nhello\r\n0\r\n\r\n')
+ }
+ finally {
+ await gateway.stop('entry')
+ await raw.close()
+ }
+ })
+
+ it('客户端声明 content-length 时按同一长度写出,上游连接上的正文长度与声明一致', async () => {
+ const raw = await rawUpstream()
+ const status = await gateway.start({ id: 'entry', kind: 'outbound', upstream: raw.origin, port: 0, tokenProvider: async authority => `http://${authority}/?token=launch-token-1` })
+ try {
+ const payload = 'GET /smuggled HTTP/1.1\r\nhost: 127.0.0.1:1\r\n\r\n'
+ const reply = await call(status.port, '/x', { method: 'GET', headers: { 'content-length': String(Buffer.byteLength(payload)) }, body: payload })
+ expect(reply.status).toBe(200)
+ const forwarded = (await raw.waitForRequests(2)).at(-1) ?? ''
+ const head = headOf(forwarded)
+ expect(head.toLowerCase()).toContain(`content-length: ${Buffer.byteLength(payload)}`)
+ expect(head.toLowerCase()).not.toContain('transfer-encoding')
+ expect(bodyOf(forwarded)).toBe(payload)
+ }
+ finally {
+ await gateway.stop('entry')
+ await raw.close()
+ }
+ })
+
+ it('无正文声明的请求不凭空添上分帧头,也不写出任何正文', async () => {
+ const raw = await rawUpstream()
+ const status = await gateway.start({ id: 'entry', kind: 'outbound', upstream: raw.origin, port: 0, tokenProvider: async authority => `http://${authority}/?token=launch-token-1` })
+ try {
+ const reply = await call(status.port, '/x')
+ expect(reply.status).toBe(200)
+ const forwarded = (await raw.waitForRequests(2)).at(-1) ?? ''
+ const head = headOf(forwarded)
+ expect(head.toLowerCase()).not.toContain('transfer-encoding')
+ expect(head.toLowerCase()).not.toContain('content-length')
+ expect(bodyOf(forwarded)).toBe('')
+ }
+ finally {
+ await gateway.stop('entry')
+ await raw.close()
+ }
+ })
+})
+
+describe('gateway 来源门禁判定矩阵(真实 HTTP 管线)', () => {
+ const CLASSES = ['loopback', 'private', 'public', 'tunnel'] as const
+
+ function headersFor(source: typeof CLASSES[number]): IncomingHttpHeaders {
+ return source === 'loopback' ? {} : markerHeaders(source)
+ }
+
+ function policyFor(mode: 'unconfigured' | 'public_only' | 'all'): (() => RemoteAuthPolicy) | undefined {
+ if (mode === 'unconfigured')
+ return undefined
+ return () => policyOf({ scope: mode, linkToken: 'link-token' })
+ }
+
+ const EXPECTED: Record<typeof CLASSES[number], { unconfigured: number, publicOnly: number, all: number }> = {
+ loopback: { unconfigured: 200, publicOnly: 200, all: 200 },
+ private: { unconfigured: 200, publicOnly: 200, all: 401 },
+ public: { unconfigured: 403, publicOnly: 401, all: 401 },
+ tunnel: { unconfigured: 403, publicOnly: 401, all: 401 },
+ }
+
+ for (const source of CLASSES) {
+ for (const mode of ['unconfigured', 'public_only', 'all'] as const) {
+ const expected = mode === 'unconfigured' ? EXPECTED[source].unconfigured : mode === 'public_only' ? EXPECTED[source].publicOnly : EXPECTED[source].all
+ it(`【矩阵】${source} × ${mode} 的表现是 ${expected}`, async () => {
+ const status = await gateway.start({
+ id: 'entry',
+ kind: 'inbound',
+ upstream: upstream.origin,
+ port: 0,
+ tokenProvider: upstream.mintUrlFor,
+ ...policyFor(mode) === undefined ? {} : { auth: policyFor(mode) },
+ })
+ const reply = await call(status.port, '/api/ping', { headers: headersFor(source) })
+ expect(reply.status).toBe(expected)
+ })
+ }
+ }
+
+ it('把物理回环来源之外的私网来源按真实 TCP 对端地址判定', async () => {
+ const external = externalAddress()
+ if (external === undefined)
+ throw new Error('本机不存在非内部 IPv4 地址,无法断言真实私网来源')
+ const status = await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: 0, host: '0.0.0.0', auth: () => policyOf({ scope: 'all' }) })
+ const reply = await new Promise<Coded>((resolve, reject) => {
+ const request = httpRequest({ host: external, port: status.port, path: '/api/ping', headers: { connection: 'close' } }, (response) => {
+ const chunks: Buffer[] = []
+ response.on('data', (chunk: Buffer) => chunks.push(chunk))
+ response.on('end', () => resolve({ status: response.statusCode ?? 0, headers: response.headers, body: Buffer.concat(chunks) }))
+ })
+ request.on('error', reject)
+ request.end()
+ })
+ expect(reply.status).toBe(401)
+ })
+
+ it('未配置认证时的导航请求得到引导页面而非空白拒绝', async () => {
+ const status = await startEntry('inbound', upstream)
+ const reply = await call(status.port, '/api/ping', { headers: markerHeaders('public', navigation()) })
+ expect(reply.status).toBe(403)
+ expect(reply.headers['content-type']).toContain('text/html')
+ expect(reply.body.toString()).toContain('访问被拒绝')
+ })
+
+ it('认证存储损坏时视为未配置认证,公网与隧道来源被拒绝并引导重设密码', async () => {
+ const corrupt: RemotePasswordRecord = { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 1000, hash: 'aGFzaA==' }
+ const status = await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ password: corrupt }) })
+ const page = await call(status.port, '/api/ping', { headers: markerHeaders('public', navigation()) })
+ expect(page.status).toBe(403)
+ expect(page.headers['content-type']).toContain('text/html')
+ expect(page.body.toString()).toContain('重新设置访问密码')
+
+ const api = await call(status.port, '/api/ping', { headers: markerHeaders('tunnel') })
+ expect(api.status).toBe(403)
+ expect(JSON.parse(api.body.toString()).error).toContain('认证存储损坏')
+
+ await expect(upgraded(status.port, '/api/remote.mux', markerHeaders('tunnel'))).rejects.toThrow('403')
+
+ const loopback = await call(status.port, '/api/ping')
+ expect(loopback.status).toBe(200)
+ })
+
+ it('认证存储损坏但有链接 Token 时仍按需认证处理', async () => {
+ const corrupt: RemotePasswordRecord = { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 1000, hash: 'aGFzaA==' }
+ const status = await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ password: corrupt, linkToken: 'link-token' }) })
+ const visitor = await call(status.port, '/?auth=link-token', { headers: markerHeaders('tunnel', navigation()) })
+ expect(visitor.status).toBe(302)
+ expect(String(visitor.headers['set-cookie'])).toContain('dsh_remote_session=')
+ })
+
+ it('需认证的导航请求得到内置登录页,API 请求得到 401 与可读错误体', async () => {
+ const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }) })
+ const page = await call(status.port, '/', { headers: markerHeaders('public', navigation()) })
+ expect(page.status).toBe(401)
+ expect(page.headers['content-type']).toContain('text/html')
+ expect(page.headers['cache-control']).toBe('no-store')
+ expect(page.headers['referrer-policy']).toBe('no-referrer')
+ expect(page.body.toString()).toContain('<form method="post">')
+
+ const api = await call(status.port, '/api/ping', { headers: markerHeaders('public') })
+ expect(api.status).toBe(401)
+ expect(JSON.parse(api.body.toString()).error).toBe('需要认证后才能访问。')
+ })
+})
+
+describe('gateway 跨站来源拦截', () => {
+ it('跨站 Origin 的请求被拒绝,绝不把外部 Origin 洗成回环 authority', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const reply = await call(status.port, '/api/ping', { headers: { origin: 'https://evil.example' } })
+ expect(reply.status).toBe(403)
+ expect(reply.body.toString()).toContain('跨站来源')
+ expect(upstream.calls).toHaveLength(0)
+ })
+
+ it('sec-Fetch-Site 为 cross-site 时即使 Origin 缺失也被拒绝', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const reply = await call(status.port, '/api/ping', { headers: { 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'no-cors' } })
+ expect(reply.status).toBe(403)
+ expect(upstream.calls).toHaveLength(0)
+ })
+
+ it('跨站的文档导航照旧放行,落地文档随即同源(壳层 iframe 与外站链接依赖它)', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const reply = await call(status.port, '/', { headers: { 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'navigate', ...navigation() } })
+ expect(reply.status).toBe(200)
+ expect(reply.body.toString()).toContain('<html>')
+ expect(upstream.calls.at(-1)?.url).toBe('/')
+ })
+
+ it('隧道腿按公网主机名判同源:Safari 这类不发 Sec-Fetch 的浏览器也能写操作', async () => {
+ const tunnel = await gateway.start({
+ id: 'tunnel',
+ kind: 'tunnel',
+ upstream: upstream.origin,
+ port: 0,
+ tokenProvider: upstream.mintUrlFor,
+ auth: () => policyOf({ linkToken: 'link-token' }),
+ publicHost: () => 's2-probe.trycloudflare.com',
+ })
+ const session = signSession('session-secret', Date.now()).value
+ const safari = await call(tunnel.port, '/api/ping', {
+ headers: { host: `127.0.0.1:${tunnel.port}`, origin: 'https://s2-probe.trycloudflare.com', cookie: `dsh_remote_session=${session}` },
+ })
+ expect(safari.status).toBe(200)
+ expect(upstream.calls.at(-1)?.headers.origin).toBe(upstream.origin)
+
+ const crossSite = await call(tunnel.port, '/api/ping', {
+ headers: { host: `127.0.0.1:${tunnel.port}`, origin: 'https://evil.example', cookie: `dsh_remote_session=${session}` },
+ })
+ expect(crossSite.status).toBe(403)
+ expect(crossSite.body.toString()).toContain('跨站来源')
+ })
+
+ it('同源 Origin 与隧道域名形式的 Host 都照旧放行并改写为回环 authority', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const same = await call(status.port, '/api/ping', { headers: { host: `127.0.0.1:${status.port}`, origin: `http://127.0.0.1:${status.port}` } })
+ expect(same.status).toBe(200)
+
+ const tunnel = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ linkToken: 'link-token' }) })
+ const session = signSession('session-secret', Date.now()).value
+ const visitor = await call(tunnel.port, '/api/ping', {
+ headers: { 'host': 's2-probe.trycloudflare.com', 'origin': 'https://s2-probe.trycloudflare.com', 'sec-fetch-site': 'same-origin', 'cookie': `dsh_remote_session=${session}` },
+ })
+ expect(visitor.status).toBe(200)
+ expect(upstream.calls.at(-1)?.headers.origin).toBe(upstream.origin)
+ })
+
+ it('跨站页面的 WebSocket 升级被拒绝且不触达上游', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ await expect(upgraded(status.port, '/api/remote.mux', { origin: 'https://evil.example' })).rejects.toThrow('403')
+ expect(upstream.upgrades).toHaveLength(0)
+ const same = await upgraded(status.port, '/api/remote.mux', { origin: `http://127.0.0.1:${status.port}` })
+ expect(same.status).toBe(101)
+ same.socket.destroy()
+ })
+
+ it('隧道腿在 Host 被 cloudflared 改写成回环 authority 后照旧放行(含全部 WebSocket 升级)', async () => {
+ const status = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ linkToken: 'link-token' }) })
+ const session = signSession('session-secret', Date.now()).value
+ const rewritten = { 'host': `127.0.0.1:${status.port}`, 'origin': 'https://s2-probe.trycloudflare.com', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'cookie': `dsh_remote_session=${session}` }
+ const api = await call(status.port, '/api/ping', { headers: rewritten })
+ expect(api.status).toBe(200)
+ expect(upstream.calls.at(-1)?.headers.origin).toBe(upstream.origin)
+
+ const live = await upgraded(status.port, '/api/remote.mux', rewritten)
+ expect(live.status).toBe(101)
+ expect(upstream.upgrades.at(-1)?.headers[GATEWAY_SOURCE_HEADER]).toBe('tunnel')
+ expect(upstream.upgrades.at(-1)?.headers[GATEWAY_SESSION_HEADER]).toBe(SESSION)
+ const greeting = await once(live.socket, 'data')
+ expect((greeting[0] as Buffer).toString()).toBe('echo:hello')
+ live.socket.destroy()
+ })
+
+ it('隧道腿 Host 被改写时只信 same-origin / none,same-site 的带凭据请求被拒绝', async () => {
+ const status = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ linkToken: 'link-token' }) })
+ const session = signSession('session-secret', Date.now()).value
+ const base = { host: `127.0.0.1:${status.port}`, origin: 'https://evil.trycloudflare.com', cookie: `dsh_remote_session=${session}` }
+ const sameSite = await call(status.port, '/api/ping', { headers: { ...base, 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors' } })
+ expect(sameSite.status).toBe(403)
+ expect(sameSite.body.toString()).toContain('跨站来源')
+ const headerless = await call(status.port, '/api/ping', { headers: base })
+ expect(headerless.status).toBe(403)
+ await expect(upgraded(status.port, '/api/remote.mux', { ...base, 'sec-fetch-site': 'same-site' })).rejects.toThrow('403')
+ expect(upstream.calls).toHaveLength(0)
+ expect(upstream.upgrades).toHaveLength(0)
+ })
+
+ it('隧道腿 Host 被改写时 same-origin / none 与文档导航照旧放行', async () => {
+ const status = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ linkToken: 'link-token' }) })
+ const session = signSession('session-secret', Date.now()).value
+ const cookie = `dsh_remote_session=${session}`
+ const sameOrigin = await call(status.port, '/api/ping', { headers: { 'host': `127.0.0.1:${status.port}`, 'origin': 'https://s2-probe.trycloudflare.com', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', cookie } })
+ expect(sameOrigin.status).toBe(200)
+ const direct = await call(status.port, '/api/ping', { headers: { 'host': `127.0.0.1:${status.port}`, 'sec-fetch-site': 'none', cookie } })
+ expect(direct.status).toBe(200)
+ const navigationRequest = await call(status.port, '/', { headers: { 'host': `127.0.0.1:${status.port}`, 'origin': 'https://evil.trycloudflare.com', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'navigate', ...navigation(), cookie } })
+ expect(navigationRequest.status).toBe(200)
+ })
+
+ it('隧道腿的隧道域名 Host 与 Origin 不一致时仍按跨站拒绝', async () => {
+ const status = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ linkToken: 'link-token' }) })
+ const session = signSession('session-secret', Date.now()).value
+ const reply = await call(status.port, '/api/ping', {
+ headers: { 'host': 's2-probe.trycloudflare.com', 'origin': 'https://evil.example', 'sec-fetch-site': 'same-origin', 'cookie': `dsh_remote_session=${session}` },
+ })
+ expect(reply.status).toBe(403)
+ expect(reply.body.toString()).toContain('跨站来源')
+ await expect(upgraded(status.port, '/api/remote.mux', { host: 's2-probe.trycloudflare.com', origin: 'https://evil.example', cookie: `dsh_remote_session=${session}` })).rejects.toThrow('403')
+ expect(upstream.upgrades).toHaveLength(0)
+ })
+})
+
+describe('gateway 认证要素', () => {
+ it('密码登录成功后签发会话并 302 回跳原始访问路径', async () => {
+ const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }), tokenProvider: upstream.mintUrlFor })
+ const login = await call(status.port, '/chat/42', {
+ method: 'POST',
+ headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', ...navigation() }),
+ body: 'password=s3cret',
+ })
+ expect(login.status).toBe(302)
+ expect(login.headers.location).toBe('/chat/42')
+ expect(login.headers['cache-control']).toBe('no-store')
+ expect(login.headers['referrer-policy']).toBe('no-referrer')
+ const cookie = (login.headers['set-cookie'] ?? [])[0] ?? ''
+ expect(cookie).toContain('HttpOnly')
+ const session = cookie.slice('dsh_remote_session='.length).split(';')[0] ?? ''
+ expect(verifySession(session, 'session-secret', Date.now())).toBe(true)
+
+ const forwarded = await call(status.port, '/api/ping', { headers: markerHeaders('public', { cookie: `dsh_remote_session=${session}` }) })
+ expect(forwarded.status).toBe(200)
+ })
+
+ it.each(['inbound', 'tunnel'] as const)('永久配对码可在 %s 入口的原登录表单手输并签发会话', async (kind) => {
+ const status = await startEntry(kind, upstream, { auth: () => policyOf({ password: null, linkToken: '01234567' }), tokenProvider: upstream.mintUrlFor })
+ const headers = markerHeaders('public', { 'sec-fetch-site': 'same-origin', ...navigation() })
+ const page = await call(status.port, '/api/ping?tab=two', { headers })
+ expect(page.status).toBe(401)
+ expect(page.body.toString()).toContain('<form method="post">')
+ expect(page.body.toString()).toContain('name="password"')
+ const login = await call(status.port, '/api/ping?tab=two', {
+ method: 'POST',
+ headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' },
+ body: 'password=01234567',
+ })
+ expect(login.status).toBe(302)
+ expect(login.headers.location).toBe('/api/ping?tab=two')
+ const cookie = (login.headers['set-cookie'] ?? [])[0] ?? ''
+ expect(cookie).toContain('HttpOnly')
+ const session = cookie.slice('dsh_remote_session='.length).split(';')[0] ?? ''
+ expect(verifySession(session, 'session-secret', Date.now())).toBe(true)
+ expect(upstream.calls).toHaveLength(0)
+ const forwarded = await call(status.port, '/api/ping?tab=two', { headers: { ...headers, cookie: `dsh_remote_session=${session}` } })
+ expect(forwarded.status).toBe(200)
+ expect(forwarded.body.toString()).toBe('{"ok":true}')
+ })
+
+ it('永久配对码撤销后原登录表单拒绝旧码', async () => {
+ let policy = policyOf({ linkToken: '01234567' })
+ const status = await startEntry('inbound', upstream, { auth: () => policy })
+ const submission = {
+ method: 'POST',
+ headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', ...navigation() }),
+ body: 'password=01234567',
+ }
+ expect((await call(status.port, '/', submission)).status).toBe(302)
+ policy = policyOf()
+ const revoked = await call(status.port, '/', submission)
+ expect(revoked.status).toBe(401)
+ expect(revoked.headers['set-cookie']).toBeUndefined()
+ expect(upstream.calls).toHaveLength(0)
+ })
+
+ it.each(['linkToken', 'pairingCode'] as const)('%s 配对码的小写 GET 与手输 POST 都签发会话', async (credential) => {
+ const policy = policyOf({ password: null, linkToken: credential === 'linkToken' ? 'AB23CD45' : 'WX67YZ89', ...credential === 'pairingCode' ? { pairingCode: 'AB23CD45' } : {} })
+ const status = await startEntry('tunnel', upstream, { auth: () => policy, tokenProvider: upstream.mintUrlFor })
+ const headers = { 'sec-fetch-site': 'same-origin', ...navigation() }
+ const replies = [
+ await call(status.port, '/?auth=ab23cd45', { headers }),
+ await call(status.port, '/api/ping?tab=two', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: 'password=ab23cd45' }),
+ ]
+ for (const [index, reply] of replies.entries()) {
+ expect(reply.status).toBe(302)
+ expect(reply.headers.location).toBe(index === 0 ? '/' : '/api/ping?tab=two')
+ expect(reply.headers['cache-control']).toBe('no-store')
+ const cookie = (reply.headers['set-cookie'] ?? [])[0] ?? ''
+ expect(cookie).toContain('HttpOnly')
+ const session = cookie.slice('dsh_remote_session='.length).split(';')[0] ?? ''
+ expect(verifySession(session, 'session-secret', Date.now())).toBe(true)
+ const forwarded = await call(status.port, '/api/ping', { headers: { ...headers, cookie: `dsh_remote_session=${session}` } })
+ expect(forwarded.status).toBe(200)
+ expect(forwarded.body.toString()).toBe('{"ok":true}')
+ }
+ })
+
+ it.each(['linkToken', 'pairingCode'] as const)('%s 配对码更换后小写 GET 与手输 POST 均拒绝旧码且已签会话仍有效', async (credential) => {
+ let policy = policyOf({ password: null, linkToken: credential === 'linkToken' ? 'AB23CD45' : 'WX67YZ89', ...credential === 'pairingCode' ? { pairingCode: 'AB23CD45' } : {} })
+ const status = await startEntry('tunnel', upstream, { auth: () => policy, tokenProvider: upstream.mintUrlFor })
+ const headers = { 'sec-fetch-site': 'same-origin', ...navigation() }
+ const hit = await call(status.port, '/?auth=AB23CD45', { headers })
+ expect(hit.status).toBe(302)
+ const cookie = (hit.headers['set-cookie'] ?? [])[0]?.split(';')[0] ?? ''
+ policy = { ...policy, [credential]: 'EF67GH89' }
+ const replies = [
+ await call(status.port, '/?auth=ab23cd45', { headers }),
+ await call(status.port, '/', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: 'password=ab23cd45' }),
+ ]
+ for (const reply of replies) {
+ expect(reply.status).toBe(401)
+ expect(reply.headers['set-cookie']).toBeUndefined()
+ }
+ expect(upstream.calls).toHaveLength(0)
+ expect((await call(status.port, '/api/ping', { headers: { ...headers, cookie } })).status).toBe(200)
+ })
+
+ it('临时配对码在五分钟到期边界拒绝旧码的 GET 与 POST,已签会话仍有效', async () => {
+ resetPairingCode()
+ const now = 1_700_000_000_000
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(now)
+ try {
+ const code = pairingCodeOf().code.toLowerCase()
+ const status = await startEntry('tunnel', upstream, { auth: () => policyOf({ password: null, linkToken: 'WX67YZ89', pairingCode: pairingCodeOf().code }), tokenProvider: upstream.mintUrlFor })
+ const headers = { 'sec-fetch-site': 'same-origin', ...navigation() }
+ const hit = await call(status.port, `/?auth=${code}`, { headers })
+ expect(hit.status).toBe(302)
+ const cookie = (hit.headers['set-cookie'] ?? [])[0]?.split(';')[0] ?? ''
+ clock.mockReturnValue(now + 299_999)
+ expect((await call(status.port, `/?auth=${code}`, { headers })).status).toBe(302)
+ clock.mockReturnValue(now + 300_000)
+ const expired = [
+ await call(status.port, `/?auth=${code}`, { headers }),
+ await call(status.port, '/', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: `password=${code}` }),
+ ]
+ expect(expired.map(reply => reply.status)).toEqual([401, 401])
+ for (const reply of expired)
+ expect(reply.headers['set-cookie']).toBeUndefined()
+ expect(upstream.calls).toHaveLength(0)
+ expect((await call(status.port, '/api/ping', { headers: { ...headers, cookie } })).status).toBe(200)
+ }
+ finally {
+ clock.mockRestore()
+ resetPairingCode()
+ }
+ })
+
+ it.each(['GET', 'POST'] as const)('临时配对码经 %s 只成功一次,旧码失效但已签会话仍有效', async (method) => {
+ const first = pairingCodeOf()
+ const policy = policyOf({ password: null, linkToken: 'WX67YZ89', pairingCode: first.code, consumePairingCode })
+ const status = await startEntry('tunnel', upstream, { auth: () => policy, tokenProvider: upstream.mintUrlFor })
+ const headers = { 'sec-fetch-site': 'same-origin', ...navigation() }
+ const path = method === 'GET' ? `/?auth=${first.code.toLowerCase()}` : '/chat/42?tab=two'
+ const options = method === 'GET' ? { headers } : { method, headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: `password=${first.code.toLowerCase()}` }
+ const login = await call(status.port, path, options)
+ expect(login.status).toBe(302)
+ expect(login.headers.location).toBe(method === 'GET' ? '/' : '/chat/42?tab=two')
+ expect(pairingCodeOf().usedSeq).toBe(1)
+ expect(pairingCodeOf().code).not.toBe(first.code)
+ const session = (login.headers['set-cookie'] ?? [])[0]?.split(';')[0] ?? ''
+ expect(session).toContain('dsh_remote_session=')
+ const reused = await call(status.port, path, options)
+ expect(reused.status).toBe(401)
+ expect(reused.headers['set-cookie']).toBeUndefined()
+ expect(pairingCodeOf().usedSeq).toBe(1)
+ expect((await call(status.port, '/api/ping', { headers: { ...headers, cookie: session } })).status).toBe(200)
+ })
+
+ it('并发 GET 与 POST 竞争同一码时只签发一份会话', async () => {
+ const first = pairingCodeOf()
+ const policy = policyOf({ password: null, linkToken: 'WX67YZ89', pairingCode: first.code, consumePairingCode })
+ const status = await startEntry('tunnel', upstream, { auth: () => policy })
+ const headers = { 'sec-fetch-site': 'same-origin', ...navigation() }
+ const replies = await Promise.all([
+ call(status.port, `/?auth=${first.code.toLowerCase()}`, { headers }),
+ call(status.port, '/', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: `password=${first.code.toLowerCase()}` }),
+ ])
+ expect(replies.map(reply => reply.status).sort()).toEqual([302, 401])
+ expect(replies.filter(reply => reply.headers['set-cookie'] !== undefined)).toHaveLength(1)
+ expect(pairingCodeOf().usedSeq).toBe(1)
+ expect(upstream.calls).toHaveLength(0)
+ })
+
+ it('永久码、密码、错误码和有效会话均不消费临时码', async () => {
+ const first = pairingCodeOf()
+ const policy = policyOf({ linkToken: first.code, pairingCode: first.code, consumePairingCode })
+ const status = await startEntry('tunnel', upstream, { auth: () => policy, tokenProvider: upstream.mintUrlFor })
+ const headers = { 'sec-fetch-site': 'same-origin', ...navigation() }
+ const permanent = await call(status.port, `/?auth=${first.code.toLowerCase()}`, { headers })
+ expect(permanent.status).toBe(302)
+ expect(pairingCodeOf()).toBe(first)
+ const password = await call(status.port, '/', { method: 'POST', headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' }, body: 'password=s3cret' })
+ expect(password.status).toBe(302)
+ expect(pairingCodeOf()).toBe(first)
+ expect((await call(status.port, '/?auth=invalid', { headers })).status).toBe(401)
+ expect(pairingCodeOf()).toBe(first)
+ const cookie = (permanent.headers['set-cookie'] ?? [])[0]?.split(';')[0] ?? ''
+ expect((await call(status.port, `/?auth=${first.code}`, { headers: { ...headers, cookie } })).status).toBe(200)
+ expect(pairingCodeOf()).toBe(first)
+ })
+
+ it('表单 body 读取期间已消费或到期的临时码不接受旧策略快照', async () => {
+ const now = 1_700_000_000_000
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(now)
+ for (const reason of ['used', 'expired'] as const) {
+ resetPairingCode()
+ clock.mockReturnValue(now)
+ const first = pairingCodeOf()
+ let reads = 0
+ const policy = policyOf({ password: null, linkToken: 'WX67YZ89', pairingCode: first.code, consumePairingCode })
+ const status = await startEntry('tunnel', upstream, { auth: () => {
+ reads += 1
+ return policy
+ } })
+ const body = `password=${first.code.toLowerCase()}`
+ const request = httpRequest({ host: '127.0.0.1', port: status.port, path: '/', method: 'POST', headers: { 'connection': 'close', 'sec-fetch-site': 'same-origin', ...navigation(), 'content-type': 'application/x-www-form-urlencoded', 'content-length': Buffer.byteLength(body) } })
+ const pending = new Promise<Coded>((resolve, reject) => {
+ request.on('response', (response) => {
+ const chunks: Buffer[] = []
+ response.on('data', (chunk: Buffer) => chunks.push(chunk))
+ response.on('end', () => resolve({ status: response.statusCode ?? 0, headers: response.headers, body: Buffer.concat(chunks) }))
+ })
+ request.on('error', reject)
+ })
+ try {
+ request.write('password=')
+ await vi.waitFor(() => expect(reads).toBeGreaterThan(0))
+ if (reason === 'used')
+ expect(consumePairingCode(first.code)).toBe(true)
+ else
+ clock.mockReturnValue(now + PAIRING_TTL_MS)
+ request.end(first.code.toLowerCase())
+ const reply = await pending
+ expect(reply.status).toBe(401)
+ expect(reply.headers['set-cookie']).toBeUndefined()
+ expect(pairingCodeOf().usedSeq).toBe(reason === 'used' ? 1 : 0)
+ }
+ finally {
+ request.destroy()
+ await pending.catch(() => undefined)
+ }
+ }
+ expect(upstream.calls).toHaveLength(0)
+ })
+
+ it('局域网免密分支仍消费根链接与根登录表单,普通 LAN 请求和回环不消费', async () => {
+ const policy = policyOf({ password: null, linkToken: 'WX67YZ89', pairingCode: pairingCodeOf().code, consumePairingCode })
+ const status = await startEntry('inbound', upstream, { auth: () => policy, tokenProvider: upstream.mintUrlFor })
+ const privateHeaders = markerHeaders('private', navigation())
+ const code = pairingCodeOf().code
+ expect((await call(status.port, '/', { headers: privateHeaders })).status).toBe(200)
+ expect((await call(status.port, `/?auth=${code}`, { headers: markerHeaders('loopback') })).status).toBe(200)
+ expect((await call(status.port, '/api/echo', { method: 'POST', headers: { ...privateHeaders, 'content-type': 'application/x-www-form-urlencoded' }, body: `password=${code}` })).status).toBe(200)
+ expect(pairingCodeOf().usedSeq).toBe(0)
+ const login = await call(status.port, `/?auth=${code.toLowerCase()}`, { headers: privateHeaders })
+ expect(login.status).toBe(302)
+ expect(pairingCodeOf().usedSeq).toBe(1)
+ expect((await call(status.port, `/?auth=${code}`, { headers: privateHeaders })).status).toBe(401)
+ const next = pairingCodeOf().code
+ const form = { method: 'POST', headers: { ...privateHeaders, 'content-type': 'application/x-www-form-urlencoded' }, body: `password=${next.toLowerCase()}` }
+ expect((await call(status.port, '/', form)).status).toBe(302)
+ expect(pairingCodeOf().usedSeq).toBe(2)
+ expect((await call(status.port, '/', form)).status).toBe(401)
+ expect(pairingCodeOf().usedSeq).toBe(2)
+ })
+
+ it('登录页表单提交到当前 URL:回跳目标不依赖 Referer(登录页声明 no-referrer)', async () => {
+ const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }), tokenProvider: upstream.mintUrlFor })
+ const page = await call(status.port, '/chat/42?tab=two', { headers: markerHeaders('public', navigation()) })
+ expect(page.status).toBe(401)
+ expect(page.body.toString()).toContain('<form method="post">')
+ const login = await call(status.port, '/chat/42?tab=two', {
+ method: 'POST',
+ headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', ...navigation() }),
+ body: 'password=s3cret',
+ })
+ expect(login.headers.referer).toBeUndefined()
+ expect(login.status).toBe(302)
+ expect(login.headers.location).toBe('/chat/42?tab=two')
+ })
+
+ it('aPI 客户端带 password 字段的 POST 不是登录提交:回 401 且不误发会话', async () => {
+ const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }) })
+ const shaped = await call(status.port, '/api/echo', {
+ method: 'POST',
+ headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', 'accept': 'application/json' }),
+ body: 'password=s3cret',
+ })
+ expect(shaped.status).toBe(401)
+ expect(shaped.headers['set-cookie']).toBeUndefined()
+ expect(JSON.parse(shaped.body.toString()).error).toBe('需要认证后才能访问。')
+
+ const notUrlencoded = await call(status.port, '/api/echo', {
+ method: 'POST',
+ headers: markerHeaders('public', { 'content-type': 'application/json', ...navigation() }),
+ body: '{"password":"s3cret"}',
+ })
+ expect(notUrlencoded.status).toBe(401)
+ expect(notUrlencoded.headers['set-cookie']).toBeUndefined()
+ expect(upstream.calls.some(entry => entry.url === '/api/echo')).toBe(false)
+ })
+
+ it('密码错误时重新渲染登录页并计入限速,连续失败触发封禁', async () => {
+ const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }) })
+ const attempt = async () => await call(status.port, '/', {
+ method: 'POST',
+ headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', ...navigation() }),
+ body: 'password=wrong',
+ })
+ const first = await attempt()
+ expect(first.status).toBe(401)
+ expect(first.body.toString()).toContain('密码不正确')
+ for (let index = 1; index < 5; index++)
+ await attempt()
+ const banned = await attempt()
+ expect(banned.status).toBe(429)
+ expect(banned.headers['retry-after']).toBeDefined()
+ expect(banned.body.toString()).toContain('认证失败次数过多')
+ })
+
+ it('链接 Token 命中即签发会话并 302 到不带参数的干净 URL', async () => {
+ const token = createLinkToken()
+ const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: token }), tokenProvider: upstream.mintUrlFor })
+ const hit = await call(status.port, `/?auth=${token}`, { headers: markerHeaders('public') })
+ expect(hit.status).toBe(302)
+ expect(hit.headers.location).toBe('/')
+ const session = ((hit.headers['set-cookie'] ?? [])[0] ?? '').slice('dsh_remote_session='.length).split(';')[0] ?? ''
+ expect(verifySession(session, 'session-secret', Date.now())).toBe(true)
+
+ const rotated = await call(status.port, '/?auth=stale-token', { headers: markerHeaders('public') })
+ expect(rotated.status).toBe(401)
+ })
+
+ it('会话 cookie 伪造或过期都不放行', async () => {
+ const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }) })
+ const forged = await call(status.port, '/api/ping', { headers: markerHeaders('public', { cookie: 'dsh_remote_session=v1.9999999999999.deadbeef' }) })
+ expect(forged.status).toBe(401)
+ const expired = signSession('session-secret', Date.now() - 60_000, 1000)
+ const stale = await call(status.port, '/api/ping', { headers: markerHeaders('public', { cookie: `dsh_remote_session=${expired.value}` }) })
+ expect(stale.status).toBe(401)
+ })
+})
+
+describe('gateway 内部来源标识', () => {
+ it('把分类与会话标识注入到本机上游,隧道入口恒定声明 tunnel', async () => {
+ const inbound = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ await call(inbound.port, '/api/ping', { headers: markerHeaders('private') })
+ expect(upstream.calls.at(-1)?.headers[GATEWAY_SOURCE_HEADER]).toBe('private')
+ expect(upstream.calls.at(-1)?.headers[GATEWAY_SESSION_HEADER]).toBe(SESSION)
+
+ const tunnel = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ linkToken: 'link-token' }) })
+ const session = signSession('session-secret', Date.now()).value
+ const forwarded = await call(tunnel.port, '/api/ping', { headers: tunnelHeaders(`dsh_remote_session=${session}`) })
+ expect(forwarded.status).toBe(200)
+ expect(upstream.calls.at(-1)?.headers[GATEWAY_SOURCE_HEADER]).toBe('tunnel')
+ expect(upstream.calls.at(-1)?.headers[GATEWAY_SESSION_HEADER]).toBe(SESSION)
+ })
+
+ it('注入前先剥离客户端自带的标识头,绝不追加成多值头', async () => {
+ const status = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ linkToken: 'link-token' }) })
+ const session = signSession('session-secret', Date.now()).value
+ const reply = await call(status.port, '/api/ping', {
+ headers: tunnelHeaders(`dsh_remote_session=${session}`, {
+ [GATEWAY_SOURCE_HEADER]: ['loopback', 'private'],
+ [GATEWAY_SESSION_HEADER]: ['forged', 'forged'],
+ }),
+ })
+ expect(reply.status).toBe(200)
+ const forwarded = upstream.calls.at(-1)?.headers ?? {}
+ expect(forwarded[GATEWAY_SOURCE_HEADER]).toBe('tunnel')
+ expect(forwarded[GATEWAY_SESSION_HEADER]).toBe(SESSION)
+ })
+
+ it('会话标识不匹配或缺失时按不可信处理,不回退到回环判定', async () => {
+ const status = await startEntry('inbound', upstream)
+ const forged = await call(status.port, '/api/ping', { headers: { [GATEWAY_SOURCE_HEADER]: 'loopback', [GATEWAY_SESSION_HEADER]: 'forged' } })
+ expect(forged.status).toBe(403)
+ const half = await call(status.port, '/api/ping', { headers: { [GATEWAY_SOURCE_HEADER]: 'loopback' } })
+ expect(half.status).toBe(403)
+ expect(upstream.calls.some(entry => entry.url === '/api/ping')).toBe(false)
+ })
+
+ it('会话标识不出现在任何事件里', async () => {
+ const events: RemoteGatewayEvent[] = []
+ const unsubscribe = gateway.subscribe(event => events.push(event))
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ await call(status.port, '/api/ping', { headers: markerHeaders('private') })
+ await call(status.port, '/api/ping', { headers: markerHeaders('public') })
+ await call(status.port, '/api/ping', { headers: { [GATEWAY_SOURCE_HEADER]: 'loopback', [GATEWAY_SESSION_HEADER]: 'forged' } })
+ unsubscribe()
+ expect(events.length).toBeGreaterThan(0)
+ expect(JSON.stringify(events)).not.toContain(SESSION)
+ })
+
+ it('会话标识不出现在任何响应里', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const replies = [
+ await call(status.port, '/api/ping', { headers: markerHeaders('private') }),
+ await call(status.port, '/api/ping', { headers: markerHeaders('public') }),
+ await call(status.port, '/', { headers: markerHeaders('public', { accept: '*/*' }) }),
+ ]
+ for (const reply of replies) {
+ expect(reply.body.toString()).not.toContain(SESSION)
+ expect(JSON.stringify(reply.headers)).not.toContain(SESSION)
+ }
+ })
+
+ it('会话标识不出现在出站到远端机器的请求里', async () => {
+ const outbound = await gateway.start({ id: 'outbound', kind: 'outbound', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor })
+ await call(outbound.port, '/api/ping', { headers: { [GATEWAY_SOURCE_HEADER]: 'loopback', [GATEWAY_SESSION_HEADER]: SESSION } })
+ const forwarded = upstream.calls.filter(entry => entry.headers.host === `127.0.0.1:${outbound.port}`)
+ expect(forwarded.length).toBeGreaterThan(0)
+ expect(JSON.stringify(forwarded)).not.toContain(SESSION)
+ })
+
+ it('隧道与管理入口只监听回环,入站才按调用方给定的地址', async () => {
+ const tunnel = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, host: '0.0.0.0' })
+ const outbound = await gateway.start({ id: 'outbound', kind: 'outbound', upstream: upstream.origin, port: 0, host: '0.0.0.0' })
+ const inbound = await gateway.start({ id: 'inbound', kind: 'inbound', upstream: upstream.origin, port: 0, host: '0.0.0.0' })
+ expect(tunnel.host).toBe('127.0.0.1')
+ expect(outbound.host).toBe('127.0.0.1')
+ expect(inbound.host).toBe('0.0.0.0')
+ })
+})
+
+describe('gateway 限速分桶', () => {
+ it('隧道来源按隧道侧声明的客户端 IP 分桶,一个访客锁不死其它访客', async () => {
+ const status = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, auth: () => policyOf({ linkToken: 'link-token' }) })
+ const attempt = async (clientIp: string) => await call(status.port, '/', {
+ method: 'POST',
+ headers: { 'cf-connecting-ip': clientIp, 'sec-fetch-site': 'same-origin', 'content-type': 'application/x-www-form-urlencoded', ...navigation() },
+ body: 'password=wrong',
+ })
+ for (let index = 0; index < 5; index++)
+ await attempt('203.0.113.7')
+ const banned = await attempt('203.0.113.7')
+ expect(banned.status).toBe(429)
+ const other = await attempt('198.51.100.9')
+ expect(other.status).toBe(401)
+ })
+
+ it('非隧道来源忽略可伪造的转发头,只按 TCP 对端分桶', async () => {
+ const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }) })
+ const attempt = async (clientIp: string) => await call(status.port, '/', {
+ method: 'POST',
+ headers: markerHeaders('public', { 'cf-connecting-ip': clientIp, 'content-type': 'application/x-www-form-urlencoded', ...navigation() }),
+ body: 'password=wrong',
+ })
+ for (let index = 0; index < 5; index++)
+ await attempt('203.0.113.7')
+ const banned = await attempt('198.51.100.9')
+ expect(banned.status).toBe(429)
+ })
+
+ it('同一分桶被封禁后,持有效会话的访客仍被放行', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor, auth: () => policyOf({ linkToken: 'link-token' }) })
+ const attempt = async () => await call(status.port, '/', {
+ method: 'POST',
+ headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', ...navigation() }),
+ body: 'password=wrong',
+ })
+ for (let index = 0; index < 6; index++)
+ await attempt()
+ const banned = await attempt()
+ expect(banned.status).toBe(429)
+
+ const session = signSession('session-secret', Date.now()).value
+ const admitted = await call(status.port, '/api/ping', { headers: markerHeaders('public', { cookie: `dsh_remote_session=${session}` }) })
+ expect(admitted.status).toBe(200)
+ })
+})
+
+describe('gateway 压缩协商', () => {
+ async function compressedEntry(): Promise<number> {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ return status.port
+ }
+
+ it('客户端声明 zstd 时返回 zstd,只声明 gzip 时返回 gzip,都不声明时返回 identity', async () => {
+ const port = await compressedEntry()
+ const zstd = await call(port, '/big', { headers: markerHeaders('private', { 'accept-encoding': 'zstd, gzip' }) })
+ expect(zstd.headers['content-encoding']).toBe('zstd')
+ expect(zstd.headers.vary).toBe('accept-encoding')
+ expect(decodeReply(zstd)).toBe('b'.repeat(MIN_BYTES * 4))
+
+ const gzip = await call(port, '/big', { headers: markerHeaders('private', { 'accept-encoding': 'gzip' }) })
+ expect(gzip.headers['content-encoding']).toBe('gzip')
+ expect(decodeReply(gzip)).toBe('b'.repeat(MIN_BYTES * 4))
+
+ const plain = await call(port, '/big', { headers: markerHeaders('private') })
+ expect(plain.headers['content-encoding']).toBeUndefined()
+ expect(plain.body.toString()).toBe('b'.repeat(MIN_BYTES * 4))
+ })
+
+ it('只接受 br 时走 identity 而不报错', async () => {
+ const port = await compressedEntry()
+ const reply = await call(port, '/big', { headers: markerHeaders('private', { 'accept-encoding': 'br' }) })
+ expect(reply.status).toBe(200)
+ expect(reply.headers['content-encoding']).toBeUndefined()
+ expect(reply.body.toString()).toBe('b'.repeat(MIN_BYTES * 4))
+ })
+
+ it('小于阈值的响应不被压缩', async () => {
+ const port = await compressedEntry()
+ const reply = await call(port, '/small', { headers: markerHeaders('private', { 'accept-encoding': 'zstd' }) })
+ expect(reply.status).toBe(200)
+ expect(reply.headers['content-encoding']).toBeUndefined()
+ expect(reply.body.toString()).toBe('tiny')
+ })
+
+ it('未知长度的小响应在未达阈值时按 identity 结束,不留下声明了编码的明文正文', async () => {
+ const port = await compressedEntry()
+ for (const coding of ['zstd', 'gzip'] as const) {
+ const reply = await call(port, '/chunked-small', { headers: markerHeaders('private', { 'accept-encoding': coding }) })
+ expect(reply.status).toBe(200)
+ expect(reply.headers['content-encoding']).toBeUndefined()
+ expect(reply.headers['content-length']).toBe(String(reply.body.length))
+ expect(reply.body.toString()).toBe('{"ok":true}')
+ }
+ })
+
+ it('不可压缩类型不被压缩', async () => {
+ const port = await compressedEntry()
+ const reply = await call(port, '/image', { headers: markerHeaders('private', { 'accept-encoding': 'zstd' }) })
+ expect(reply.status).toBe(200)
+ expect(reply.headers['content-encoding']).toBeUndefined()
+ expect(reply.body.length).toBe(MIN_BYTES * 2)
+ })
+
+ it('未知长度的大响应在达到阈值后才开始压缩', async () => {
+ const port = await compressedEntry()
+ const reply = await call(port, '/chunked', { headers: markerHeaders('private', { 'accept-encoding': 'zstd' }) })
+ expect(reply.headers['content-encoding']).toBe('zstd')
+ expect(reply.headers['content-length']).toBeUndefined()
+ expect(decodeReply(reply)).toBe(`${'c'.repeat(MIN_BYTES)}${'d'.repeat(MIN_BYTES)}`)
+ })
+
+ it('上游已 gzip 而客户端只接受 zstd 时解压后按 zstd 重压并重算长度', async () => {
+ const port = await compressedEntry()
+ const reply = await call(port, '/gz', { headers: markerHeaders('private', { 'accept-encoding': 'zstd' }) })
+ expect(reply.headers['content-encoding']).toBe('zstd')
+ expect(reply.headers['content-length']).toBeUndefined()
+ expect(decodeReply(reply)).toBe('g'.repeat(MIN_BYTES * 2))
+ })
+
+ it('上游编码在下游可接受集合内时原样透传,不做二次压缩', async () => {
+ const port = await compressedEntry()
+ const reply = await call(port, '/gz', { headers: markerHeaders('private', { 'accept-encoding': 'gzip' }) })
+ expect(reply.headers['content-encoding']).toBe('gzip')
+ expect(reply.headers['content-length']).toBe(String(reply.body.length))
+ expect(zlib.gunzipSync(reply.body).toString()).toBe('g'.repeat(MIN_BYTES * 2))
+ })
+
+ it('本地回环腿一律 identity,即使客户端声明了 zstd', async () => {
+ const port = await compressedEntry()
+ const reply = await call(port, '/big', { headers: { 'accept-encoding': 'zstd' } })
+ expect(reply.status).toBe(200)
+ expect(reply.headers['content-encoding']).toBeUndefined()
+ expect(reply.body.toString()).toBe('b'.repeat(MIN_BYTES * 4))
+ })
+})
+
+describe('gateway SSE 流式压缩', () => {
+ it('逐块 flush:第二个分片尚未写出时第一个分片已经到达', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const reply = await streamed(status.port, '/sse', markerHeaders('private', { 'accept-encoding': 'zstd' }))
+ expect(reply.status).toBe(200)
+ expect(reply.headers['content-encoding']).toBe('zstd')
+ expect(reply.headers['content-length']).toBeUndefined()
+
+ const decoded = reply.stream.pipe(zlib.createZstdDecompress())
+ let text = ''
+ decoded.on('data', (chunk: Buffer) => {
+ text += chunk.toString('utf8')
+ })
+ await vi.waitFor(() => expect(text).toContain('data: one'))
+ expect(text).not.toContain('data: two')
+ upstream.releaseEvents()
+ await vi.waitFor(() => expect(text).toContain('data: two'))
+ })
+
+ it('只接受 gzip 的客户端同样得到逐块到达的 SSE', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const reply = await streamed(status.port, '/sse', markerHeaders('private', { 'accept-encoding': 'gzip' }))
+ expect(reply.headers['content-encoding']).toBe('gzip')
+ const decoded = reply.stream.pipe(zlib.createGunzip())
+ let text = ''
+ decoded.on('data', (chunk: Buffer) => {
+ text += chunk.toString('utf8')
+ })
+ await vi.waitFor(() => expect(text).toContain('data: one'))
+ expect(text).not.toContain('data: two')
+ upstream.releaseEvents()
+ await vi.waitFor(() => expect(text).toContain('data: two'))
+ })
+})
+
+describe('gateway 流中断与泄漏防护', () => {
+ it('sSE 中途断开时终止压缩流并结束响应,不残留连接', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const live = await streamed(status.port, '/sse', markerHeaders('private', { 'accept-encoding': 'zstd' }))
+ expect(live.status).toBe(200)
+ await vi.waitFor(() => expect(gateway.status('entry')?.connections).toBe(1))
+ live.stream.destroy()
+ await vi.waitFor(() => expect(gateway.status('entry')?.connections).toBe(0))
+ const after = await call(status.port, '/api/ping', { headers: markerHeaders('private') })
+ expect(after.status).toBe(200)
+ })
+
+ it('关闭入口后端口立即可被重新占用', async () => {
+ const free = await freePort()
+ const preferred = free.port
+ await free.release()
+ await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: preferred })
+ await gateway.stop('entry')
+ const reused = await freePortAt(preferred)
+ expect(reused, '关闭后端口应无残留占用').toBeDefined()
+ await reused?.release()
+ })
+})
+
+describe('gateway 上游响应中途断流', () => {
+ it('未知长度且已达阈值:终止该响应,不把客户端永久挂起', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const outcome = await observed(status.port, '/abort-big', markerHeaders('private', { 'accept-encoding': 'zstd' }))
+ expect(outcome.kind).not.toBe('no-response')
+ expect(outcome.bodyLength).toBeLessThan(MIN_BYTES * 4)
+ await vi.waitFor(() => expect(gateway.status('entry')?.connections).toBe(0))
+ })
+
+ it('未知长度且未达阈值:回可读 502,而不是伪装成完整的 200', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const outcome = await observed(status.port, '/abort-small', markerHeaders('private', { 'accept-encoding': 'zstd' }), 3000)
+ expect(outcome.kind).toBe('end')
+ expect(outcome.status).toBe(502)
+ expect(outcome.bodyLength).toBeGreaterThan(0)
+ })
+
+ it('上游断流只影响该条响应,记录事件且连接不残留', async () => {
+ const events: RemoteGatewayEvent[] = []
+ const unsubscribe = gateway.subscribe(event => events.push(event))
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ await observed(status.port, '/abort-small', markerHeaders('private', { 'accept-encoding': 'zstd' }), 3000)
+ unsubscribe()
+ expect(events.some(event => event.kind === 'compression' && event.line.includes('上游响应流错误'))).toBe(true)
+ await vi.waitFor(() => expect(gateway.status('entry')?.connections).toBe(0))
+ const after = await call(status.port, '/api/ping', { headers: markerHeaders('private') })
+ expect(after.status).toBe(200)
+ })
+
+ it('上游已 gzip 而下游只接受 zstd:中途断流被终止并记录,不永久挂起', async () => {
+ const events: RemoteGatewayEvent[] = []
+ const unsubscribe = gateway.subscribe(event => events.push(event))
+ try {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const outcome = await observed(status.port, '/gz-abort', markerHeaders('private', { 'accept-encoding': 'zstd' }), 3000)
+ expect(outcome.kind).not.toBe('no-response')
+ expect(outcome.bodyLength).toBeLessThan(MIN_BYTES * 4)
+ await vi.waitFor(() => expect(events.some(event => event.kind === 'compression' && event.line.includes('响应流中断'))).toBe(true))
+ await vi.waitFor(() => expect(gateway.status('entry')?.connections).toBe(0))
+ const after = await call(status.port, '/api/ping', { headers: markerHeaders('private') })
+ expect(after.status).toBe(200)
+ }
+ finally {
+ unsubscribe()
+ }
+ })
+
+ it('上游已 gzip 的 SSE 中途断流:终止压缩流并结束响应,不残留监听', async () => {
+ const events: RemoteGatewayEvent[] = []
+ const unsubscribe = gateway.subscribe(event => events.push(event))
+ try {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const outcome = await observed(status.port, '/gz-sse-abort', markerHeaders('private', { 'accept-encoding': 'zstd' }), 3000)
+ expect(outcome.kind).not.toBe('no-response')
+ await vi.waitFor(() => expect(events.some(event => event.kind === 'compression' && event.line.includes('响应流中断'))).toBe(true))
+ await vi.waitFor(() => expect(gateway.status('entry')?.connections).toBe(0))
+ }
+ finally {
+ unsubscribe()
+ }
+ })
+})
+
+describe('gateway 处理失败边界', () => {
+ it('登录请求体被客户端中途掐断时不产生未捕获拒绝,也不触达上游', async () => {
+ const status = await startEntry('inbound', upstream, { auth: () => policyOf({ linkToken: 'link-token' }) })
+ const rejections: string[] = []
+ const onRejection = (reason: unknown): void => {
+ rejections.push(String(reason))
+ }
+ process.on('unhandledRejection', onRejection)
+ try {
+ await new Promise<void>((resolve) => {
+ const request = httpRequest({
+ host: '127.0.0.1',
+ port: status.port,
+ path: '/',
+ method: 'POST',
+ headers: markerHeaders('public', { 'content-type': 'application/x-www-form-urlencoded', 'content-length': '4096', 'connection': 'close', ...navigation() }),
+ })
+ request.on('error', () => resolve())
+ request.on('response', (response) => {
+ response.resume()
+ response.on('end', () => resolve())
+ response.on('aborted', () => resolve())
+ })
+ request.write('password=s3c')
+ setTimeout(() => {
+ request.destroy()
+ resolve()
+ }, 100)
+ })
+ // unhandledRejection 在 promise 链落到事件循环下一轮后才触发,这里只做一次固定观察窗口;
+ // 用 vi.waitFor 会立即读出空数组而失去意义,因此保留真实等待。
+ await new Promise(resolve => setTimeout(resolve, 300))
+ }
+ finally {
+ process.off('unhandledRejection', onRejection)
+ }
+ expect(rejections).toEqual([])
+ expect(upstream.calls).toHaveLength(0)
+ await vi.waitFor(() => expect(gateway.status('entry')?.connections).toBe(0))
+ })
+
+ it('订阅者抛错不影响转发,也不打挂宿主', async () => {
+ const unsubscribe = gateway.subscribe(() => {
+ throw new Error('消费者故障')
+ })
+ try {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const reply = await call(status.port, '/api/ping', { headers: markerHeaders('private') })
+ expect(reply.status).toBe(200)
+ }
+ finally {
+ unsubscribe()
+ }
+ })
+})
+
+describe('gateway Upgrade 例外', () => {
+ it('升级请求不做压缩,但改写与注入照旧生效', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const reply = await upgraded(status.port, '/api/remote.mux', markerHeaders('private', { origin: `http://127.0.0.1:${status.port}` }))
+ expect(reply.status).toBe(101)
+ expect(reply.headers['content-encoding']).toBeUndefined()
+ const seen = upstream.upgrades.at(-1)
+ expect(seen?.headers.host).toBe(`127.0.0.1:${upstream.port}`)
+ expect(seen?.headers.origin).toBe(`http://127.0.0.1:${upstream.port}`)
+ expect(grantedCookieOf(seen?.headers ?? {})).toMatch(/^mint-/)
+ expect(seen?.headers[GATEWAY_SOURCE_HEADER]).toBe('private')
+ expect(seen?.headers[GATEWAY_SESSION_HEADER]).toBe(SESSION)
+
+ const greeting = await once(reply.socket, 'data')
+ expect((greeting[0] as Buffer).toString()).toBe('echo:hello')
+ reply.socket.write('ping')
+ const echoed = await once(reply.socket, 'data')
+ expect((echoed[0] as Buffer).toString()).toBe('echo:ping')
+ reply.socket.destroy()
+ })
+
+ it.each([false, true])('出站 WS 写入非授权标记,远端回环不能取得本机来源或秘密(伪回环=%s)', async (forged) => {
+ const status = await startEntry('outbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const reply = await upgraded(status.port, '/api/remote.mux', {
+ 'origin': `http://127.0.0.1:${status.port}`,
+ 'accept-encoding': 'zstd, gzip',
+ ...(forged ? markerHeaders('loopback') : {}),
+ })
+ expect(reply.status).toBe(101)
+ const seen = upstream.upgrades.at(-1)?.headers ?? {}
+ expect(seen.host).toBe(`127.0.0.1:${status.port}`)
+ expect(seen.origin).toBe(`http://127.0.0.1:${status.port}`)
+ expect(grantedCookieOf(seen)).toMatch(/^mint-/)
+ expect(seen['accept-encoding']).toBe('identity')
+ expect(seen[GATEWAY_SOURCE_HEADER]).toBe('public')
+ expect(seen[GATEWAY_SESSION_HEADER]).toBe('outbound')
+ expect(JSON.stringify(seen)).not.toContain(SESSION)
+ for (const remoteSession of ['', 'remote-session', 'outbound']) {
+ expect(classifySource(seen, '127.0.0.1', remoteSession)).toBe('public')
+ expect(classifySource(seen, '::1', remoteSession)).toBe('public')
+ expect(classifySource(seen, '::ffff:127.0.0.1', remoteSession)).toBe('public')
+ }
+
+ const greeting = await once(reply.socket, 'data')
+ expect((greeting[0] as Buffer).toString()).toBe('echo:hello')
+ reply.socket.destroy()
+ })
+
+ it('关闭入口时在途的升级长连接被终止', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const reply = await upgraded(status.port, '/api/remote.mux', markerHeaders('private'))
+ expect(reply.status).toBe(101)
+ const terminated = new Promise<string>((resolve) => {
+ reply.socket.on('close', () => resolve('closed'))
+ reply.socket.on('error', () => resolve('closed'))
+ reply.socket.resume()
+ })
+ const started = Date.now()
+ await gateway.stop('entry')
+ expect(Date.now() - started).toBeLessThan(2000)
+ expect(await terminated).toBe('closed')
+ expect(gateway.status('entry')).toMatchObject({ state: 'stopped', connections: 0 })
+ })
+
+ it('升级连接被客户端强行中断后网关仍然可用', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const reply = await upgraded(status.port, '/api/remote.mux', markerHeaders('private'))
+ expect(reply.status).toBe(101)
+ reply.socket.destroy()
+ await vi.waitFor(() => expect(gateway.status('entry')?.connections).toBe(0))
+ const after = await call(status.port, '/api/ping', { headers: markerHeaders('private') })
+ expect(after.status).toBe(200)
+ })
+
+ it('慢上游应答前客户端断开的升级请求被归位:连接数归零且不残留握手定时器', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ expect((await call(status.port, '/api/ping', { headers: markerHeaders('private') })).status).toBe(200)
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ try {
+ const baseline = vi.getTimerCount()
+ const sockets: Duplex[] = []
+ for (let index = 0; index < 3; index++)
+ sockets.push(await stalledUpgrade(status.port, markerHeaders('private')))
+ await until(() => upstream.upgrades.filter(entry => entry.url === '/stall').length === 3)
+ expect(vi.getTimerCount()).toBe(baseline + 3)
+ await Promise.all(sockets.map(async socket => await disconnect(socket)))
+ await until(() => gateway.status('entry')?.connections === 0)
+ expect(vi.getTimerCount()).toBe(baseline)
+ }
+ finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('冷缓存铸造窗口内客户端断开:不再向上游发起升级,连接数归零且不残留握手定时器', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ expect((await call(status.port, '/api/ping', { headers: markerHeaders('private') })).status).toBe(200)
+ let renew = false
+ let release = (): void => {}
+ const pending = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ const provider = vi.fn(async (authority: string) => {
+ if (renew)
+ await pending
+ return await upstream.mintUrlFor(authority)
+ })
+ await gateway.stop('entry')
+ const restarted = await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: 0, tokenProvider: provider })
+ renew = true
+ const before = upstream.upgrades.length
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ try {
+ const sockets: Duplex[] = []
+ for (let index = 0; index < 3; index++)
+ sockets.push(await stalledUpgrade(restarted.port, markerHeaders('private')))
+ await until(() => gateway.status('entry')?.connections === 3)
+ const baseline = vi.getTimerCount()
+ await until(() => provider.mock.calls.length === 1)
+ await Promise.all(sockets.map(async socket => await disconnect(socket)))
+ await until(() => gateway.status('entry')?.connections === 0)
+ expect(upstream.upgrades.length).toBe(before)
+ release()
+ await until(() => vi.getTimerCount() <= baseline)
+ expect(vi.getTimerCount()).toBe(baseline)
+ await until(() => upstream.calls.length > 0)
+ expect(upstream.upgrades.length).toBe(before)
+ }
+ finally {
+ vi.runOnlyPendingTimers()
+ vi.useRealTimers()
+ }
+ })
+
+ it('token provider 永不 settle 时铸造不再挂死:按 token 超时结束本次铸造,客户端拿到可读响应', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ try {
+ const status = await startEntry('inbound', upstream, { tokenProvider: async () => await new Promise<string>(() => {}) })
+ const received: string[] = []
+ const socket = connect(status.port, '127.0.0.1', () => {
+ socket.write(`GET /api/remote.mux HTTP/1.1\r\nhost: 127.0.0.1:${status.port}\r\nconnection: Upgrade\r\nupgrade: websocket\r\n${GATEWAY_SOURCE_HEADER}: private\r\n${GATEWAY_SESSION_HEADER}: ${SESSION}\r\n\r\n`)
+ })
+ socket.on('data', (chunk: Buffer) => received.push(chunk.toString('utf8')))
+ socket.on('error', () => {})
+ await until(() => gateway.status('entry')?.connections === 1)
+ await turns(4)
+ expect(upstream.upgrades).toHaveLength(0)
+ await vi.advanceTimersByTimeAsync(10_001)
+ await until(() => received.length > 0)
+ const text = received.join('')
+ expect(text.split('\r\n')[0]).toBe('HTTP/1.1 401 Unauthorized')
+ expect(text.toLowerCase()).toContain('connection: close')
+ expect(text.toLowerCase()).toContain('content-length: 0')
+ expect(text.toLowerCase()).not.toContain('transfer-encoding')
+ socket.destroy()
+ }
+ finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('未通过门禁的升级请求被拒绝且不触达上游', async () => {
+ const status = await startEntry('inbound', upstream)
+ const before = upstream.upgrades.length
+ await expect(upgraded(status.port, '/api/remote.mux', markerHeaders('public'))).rejects.toThrow('403')
+ expect(upstream.upgrades.length).toBe(before)
+ })
+
+ it('隧道入口自报来源头也拿不到门禁豁免:需认证的隧道请求按 401 拦下且不触达上游', async () => {
+ const status = await gateway.start({ id: 'tunnel', kind: 'tunnel', upstream: upstream.origin, port: 0, tokenProvider: upstream.mintUrlFor, auth: () => policyOf() })
+ const before = upstream.calls.length
+ const reply = await call(status.port, '/api/ping', { headers: { ...tunnelHeaders(''), [GATEWAY_SOURCE_HEADER]: 'loopback', [GATEWAY_SESSION_HEADER]: SESSION } })
+ expect(reply.status).toBe(401)
+ expect(upstream.calls.length).toBe(before)
+ })
+
+ it('上游声明 content-length 拒绝升级时按声明长度重新组帧,不写出重复的长度头', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const raw = await rawUpgrade(status.port, '/upgrade-403', markerHeaders('private'))
+ expect(raw.head).toBe('HTTP/1.1 403 Forbidden\r\ncontent-type: text/plain\r\nconnection: close\r\ncontent-length: 18')
+ expect(raw.body).toBe('denied by upstream')
+ })
+
+ it('401 重铸窗口内客户端断开:不再向上游发起重试升级,连接数归零且不残留握手定时器', async () => {
+ let slow = false
+ let release = (): void => {}
+ const pending = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ const provider = vi.fn(async (authority: string) => {
+ if (slow)
+ await pending
+ return await upstream.mintUrlFor(authority)
+ })
+ const status = await startEntry('inbound', upstream, { tokenProvider: provider })
+ const headers = markerHeaders('private')
+ const warm = await upgraded(status.port, '/api/remote.mux', headers)
+ expect(warm.status).toBe(101)
+ warm.socket.destroy()
+ upstream.restart()
+ slow = true
+ const before = upstream.upgrades.filter(entry => entry.url === '/retry').length
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ try {
+ const sockets = [await stalledUpgrade(status.port, { ...headers }, '/retry'), await stalledUpgrade(status.port, { ...headers }, '/retry')]
+ await until(() => upstream.upgrades.filter(entry => entry.url === '/retry').length === before + 2)
+ await until(() => provider.mock.calls.length === 3)
+ const baseline = vi.getTimerCount()
+ await Promise.all(sockets.map(async socket => await disconnect(socket)))
+ await until(() => gateway.status('entry')?.connections === 0)
+ release()
+ await until(() => vi.getTimerCount() <= baseline)
+ expect(vi.getTimerCount()).toBe(baseline)
+ expect(upstream.upgrades.filter(entry => entry.url === '/retry').length).toBe(before + 2)
+ }
+ finally {
+ vi.runOnlyPendingTimers()
+ vi.useRealTimers()
+ }
+ })
+
+ it('上游以分块拒绝升级时剥离逐跳头,只靠 connection: close 与 EOF 定界收束连接', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const raw = await rawUpgrade(status.port, '/upgrade-404', markerHeaders('private'))
+ expect(raw.head).toBe('HTTP/1.1 404 Not Found\r\ncontent-type: text/plain\r\nconnection: close')
+ expect(raw.head.toLowerCase()).not.toContain('transfer-encoding')
+ expect(raw.head.toLowerCase()).not.toContain('content-length')
+ expect(raw.body).toBe('denied by upstream')
+ })
+
+ it('升级首轮 401 时重铸 cookie 并重试成功,失败与重试各触达上游一次', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const live = await upgraded(status.port, '/api/remote.mux', markerHeaders('private'))
+ expect(live.status).toBe(101)
+ live.socket.destroy()
+
+ upstream.restart()
+ const retried = await upgraded(status.port, '/api/remote.mux', markerHeaders('private'))
+ expect(retried.status).toBe(101)
+ expect(upstream.upgrades).toHaveLength(3)
+ const stale = grantedCookieOf(upstream.upgrades[1]?.headers ?? {})
+ const headers = upstream.upgrades.at(-1)?.headers ?? {}
+ expect(stale).toMatch(/^mint-/)
+ expect(grantedCookieOf(headers)).not.toBe(stale)
+ expect(grantedCookieOf(headers)).toMatch(/^mint-/)
+ retried.socket.destroy()
+ })
+
+ it('上游迟迟不响应升级时按短超时回 504 并结束该连接', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ try {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const response = new Promise<string>((resolve, reject) => {
+ const socket = connect(status.port, '127.0.0.1', () => socket.write(`GET /stall HTTP/1.1\r\nhost: 127.0.0.1:${status.port}\r\nconnection: Upgrade\r\nupgrade: websocket\r\n${GATEWAY_SOURCE_HEADER}: private\r\n${GATEWAY_SESSION_HEADER}: ${SESSION}\r\n\r\n`))
+ const chunks: Buffer[] = []
+ socket.on('data', (chunk: Buffer) => {
+ chunks.push(chunk)
+ resolve(Buffer.concat(chunks).toString('utf8'))
+ })
+ socket.on('error', reject)
+ })
+ await upstream.waitForStall()
+ await vi.advanceTimersByTimeAsync(30_001)
+ const text = await settledTextOf(response)
+ expect(text.split('\r\n')[0]).toBe('HTTP/1.1 504 Gateway Timeout')
+ expect(text).toContain(upstream.origin)
+ }
+ finally {
+ vi.useRealTimers()
+ }
+ })
+})
+
+describe('gateway 监听生命周期', () => {
+ it('端口占用时回落到下一个可用端口,状态与入口 URL 反映真实端口', async () => {
+ const occupied = await occupiedPortWithFreeNext()
+ const status = await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: occupied.port, tokenProvider: upstream.mintUrlFor })
+ try {
+ expect(status.port).toBe(occupied.port + 1)
+ expect(status.url).toBe(`http://127.0.0.1:${occupied.port + 1}`)
+ const reply = await call(status.port, '/api/ping')
+ expect(reply.status).toBe(200)
+ }
+ finally {
+ await occupied.release()
+ }
+ })
+
+ it('请求临时端口 0 时正常绑定,不发出假的端口回落事件', async () => {
+ const events: RemoteGatewayEvent[] = []
+ const unsubscribe = gateway.subscribe(event => events.push(event))
+ try {
+ const status = await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: 0 })
+ expect(status.port).toBeGreaterThan(0)
+ }
+ finally {
+ unsubscribe()
+ }
+ expect(events.filter(event => event.kind === 'port')).toHaveLength(0)
+ })
+
+ it('优选端口为空闲时直接绑定,不发出端口回落事件', async () => {
+ await withReservedPort(async (preferred) => {
+ const events: RemoteGatewayEvent[] = []
+ const unsubscribe = gateway.subscribe(event => events.push(event))
+ try {
+ const status = await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: preferred })
+ expect(status.port).toBe(preferred)
+ }
+ finally {
+ unsubscribe()
+ }
+ expect(events.filter(event => event.kind === 'port')).toHaveLength(0)
+ })
+ })
+
+ it('进程内端口登记表阻止两个入口抢同一个端口', async () => {
+ const first = await gateway.start({ id: 'inbound', kind: 'inbound', upstream: upstream.origin, port: 0 })
+ const second = await gateway.start({ id: 'machine', kind: 'outbound', upstream: upstream.origin, port: first.port })
+ expect(second.port).not.toBe(first.port)
+ expect(gateway.list().map(entry => entry.port).filter(port => port !== 0)).toHaveLength(2)
+ })
+
+ it('端口全部占用时保持关闭状态并报告可读错误', async () => {
+ const holders = await occupyRange(21)
+ const base = holders[0]?.port ?? 0
+ try {
+ // 错误码是消费方(出站机器)判定「终态、不再重试」的契约,与中文文案解耦
+ await expect(gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: base })).rejects.toMatchObject({
+ code: 'ERR_GATEWAY_PORTS_EXHAUSTED',
+ message: expect.stringMatching(/网关端口全部占用/u),
+ })
+ expect(gateway.status('entry')).toMatchObject({ state: 'stopped', port: 0 })
+ }
+ finally {
+ for (const holder of holders)
+ await holder.release()
+ }
+ })
+
+ it('重复开启同一入口时先关旧再开新,端口不残留', async () => {
+ const free = await freePort()
+ const preferred = free.port
+ await free.release()
+ const first = await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: preferred })
+ const second = await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: preferred })
+ expect(first.port).toBe(preferred)
+ expect(second.port).toBe(preferred)
+ expect(gateway.list()).toHaveLength(1)
+ })
+
+ it('关闭入口后立即停止接受连接,并在秒级终止在途长连接', async () => {
+ const status = await startEntry('inbound', upstream, { tokenProvider: upstream.mintUrlFor })
+ const live = await streamed(status.port, '/sse', markerHeaders('private'))
+ expect(live.status).toBe(200)
+ const terminated = new Promise<string>((resolve) => {
+ live.stream.on('close', () => resolve('closed'))
+ live.stream.on('error', () => resolve('closed'))
+ live.stream.resume()
+ })
+ const started = Date.now()
+ await gateway.stop('entry')
+ expect(Date.now() - started).toBeLessThan(2000)
+ expect(await terminated).toBe('closed')
+ expect(gateway.status('entry')).toMatchObject({ state: 'stopped', port: 0, connections: 0 })
+ await expect(call(status.port, '/api/ping')).rejects.toThrow()
+ })
+
+ it('dispose 关闭全部入口并清空状态', async () => {
+ await gateway.start({ id: 'inbound', kind: 'inbound', upstream: upstream.origin, port: 0 })
+ await gateway.start({ id: 'machine', kind: 'outbound', upstream: upstream.origin, port: 0 })
+ expect(gateway.list()).toHaveLength(2)
+ await gateway.dispose()
+ expect(gateway.list()).toHaveLength(0)
+ expect(gateway.status('inbound')).toBeUndefined()
+ })
+
+ it('生命周期事件只在真实状态变化时发出,重复停止不再发第二条', async () => {
+ const events: RemoteGatewayEvent[] = []
+ const unsubscribe = gateway.subscribe(event => events.push(event))
+ await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: 0 })
+ await gateway.stop('entry')
+ await gateway.stop('entry')
+ unsubscribe()
+ const stops = events.filter(event => event.kind === 'stopped')
+ expect(stops).toHaveLength(1)
+ expect(stops[0]?.line).not.toContain(':0')
+ })
+
+ it('dispose 不回收事件序号,消费者按 sinceSeq 增量拉取不会错序', async () => {
+ const events: RemoteGatewayEvent[] = []
+ const unsubscribe = gateway.subscribe(event => events.push(event))
+ await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: 0 })
+ const before = events.at(-1)?.seq ?? 0
+ await gateway.dispose()
+ await gateway.start({ id: 'entry', kind: 'inbound', upstream: upstream.origin, port: 0 })
+ unsubscribe()
+ const seqs = events.map(event => event.seq)
+ expect(seqs).toEqual([...seqs].sort((left, right) => left - right))
+ expect(new Set(seqs).size).toBe(seqs.length)
+ expect(events.at(-1)?.seq).toBeGreaterThan(before)
+ })
+})
+
+// --- test helpers ---
+function externalAddress(): string | undefined {
+ return Object.values(networkInterfaces())
+ .flat()
+ .find(entry => entry !== undefined && !entry.internal && entry.family === 'IPv4' && !entry.address.startsWith('127.'))
+ ?.address
+}
+
+/** 绑定一个刚释放的固定端口:抢占窗口只有释放到监听的几毫秒,冲突时换端口重试整段。 */
+async function withReservedPort<T>(body: (port: number) => Promise<T>): Promise<T> {
+ let lastError: unknown
+ for (let attempt = 0; attempt < 5; attempt++) {
+ const free = await freePort()
+ const port = free.port
+ await free.release()
+ try {
+ return await body(port)
+ }
+ catch (error) {
+ lastError = error
+ if (!String(error).includes('EADDRINUSE'))
+ throw error
+ }
+ }
+ throw lastError
+}
+
+function freePortAt(port: number): Promise<{ port: number, release: () => Promise<void> } | undefined> {
+ const server = createNetServer()
+ return new Promise((resolve) => {
+ server.once('error', () => resolve(undefined))
+ server.listen(port, '127.0.0.1', () => {
+ resolve({ port, release: () => new Promise<void>((done) => {
+ server.close(() => done())
+ }) })
+ })
+ })
+}
+
+/** 占用 P 且保证 P+1 空闲,使「回落到下一个可用端口」有唯一确定的期望值。 */
+async function occupiedPortWithFreeNext(): Promise<{ port: number, release: () => Promise<void> }> {
+ for (let attempt = 0; attempt < 5; attempt++) {
+ const base = await freePort()
+ const next = await freePortAt(base.port + 1)
+ if (next !== undefined) {
+ await next.release()
+ return base
+ }
+ await base.release()
+ }
+ throw new Error('连续端口不可得')
+}
+
+async function occupyRange(size: number): Promise<Array<{ port: number, release: () => Promise<void> }>> {
+ for (let attempt = 0; attempt < 5; attempt++) {
+ const base = await freePort()
+ const holders = [base]
+ let complete = true
+ for (let offset = 1; offset < size; offset++) {
+ const holder = await freePortAt(base.port + offset)
+ if (holder === undefined) {
+ complete = false
+ break
+ }
+ holders.push(holder)
+ }
+ if (complete)
+ return holders
+ for (const holder of holders)
+ await holder.release()
+ }
+ throw new Error(`无法连续占满 ${size} 个端口`)
+}
diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.ts b/packages/dsh-tauri-remote/src/host/service/gateway.ts
new file mode 100644
index 00000000..1fda0a61
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/gateway.ts
@@ -0,0 +1,976 @@
+import type { ClientRequest, IncomingMessage, OutgoingHttpHeaders, Server, ServerResponse } from 'node:http'
+import type { Duplex, Readable, Transform, Writable } from 'node:stream'
+import type { RemoteAuthFailureRecord, RemoteAuthPolicy, RemoteGatewayEntryKind, RemoteGatewayEntryStatus, RemoteGatewayEvent, RemoteGatewayEventKind, RemoteGatewayStartOptions, RemoteGatewayTokenProvider, RemoteSessionTicket, RemoteSourceClass } from '../types/index'
+import { Buffer } from 'node:buffer'
+import { createServer, request as httpRequest } from 'node:http'
+import { pipeline } from 'node:stream'
+import { defineService } from 'dsh-tauri'
+import { messageOf } from '../../shared/error'
+import { ensureSourceSession } from '../config/runtime'
+import { rateLimitAfterFailure, rateLimitBlockedMs, signSession, tokenMatches, verifyPassword, verifySession } from '../utils/auth'
+import { classifySource, decideSourceAccess, isAuthConfigured, isAuthStorageBroken, rateLimitKeyOf } from '../utils/source'
+import { authorityFor, cookiePairsOf, createCompressor, createDecompressor, deniedHtml, entryUrlOf, forwardHeadersOf, isCrossSiteRequest, isNavigationRequest, isReplayable, isUpgradeOf, loginPageHtml, mergeCookieHeader, parseCookieHeader, parseFormField, responseHeadersOf, responsePlanOf, supportsZstd, tunnelClientIpOf, upstreamPortOf } from './gateway.utils'
+
+const LOOPBACK = '127.0.0.1'
+
+const PORT_FALLBACK_LIMIT = 20
+
+const PORTS_EXHAUSTED_CODE = 'ERR_GATEWAY_PORTS_EXHAUSTED'
+
+const COMPRESS_MIN_BYTES = 1024
+
+const SESSION_COOKIE = 'dsh_remote_session'
+
+const AUTH_QUERY = 'auth'
+
+const LOGIN_FIELD = 'password'
+
+const FORM_BODY_LIMIT = 4096
+
+const SHORT_TIMEOUT_MS = 30_000
+
+const LONG_TIMEOUT_MS = 300_000
+
+const MINT_TIMEOUT_MS = 10_000
+
+const TOKEN_TIMEOUT_MS = 10_000
+
+const DENIED_REASON = '尚未配置访问认证(密码或链接 Token),公网与隧道来源一律拒绝。请在本机回环来源的「远程 → 访问入口」中设置访问密码或链接 Token。'
+
+const BROKEN_AUTH_REASON = '认证存储损坏,已视为未配置访问认证:公网与隧道来源一律拒绝。请在本机回环来源的「远程 → 访问入口」中重新设置访问密码。'
+
+const CROSS_SITE_REASON = '跨站来源的请求被拒绝:请用访问链接里的同一域名打开页面后重试;若你是在别的站点里嵌入访问地址,改成本机回环来源或带 ?auth= 的链接。'
+
+const BANNED_REASON = '认证失败次数过多,请稍后重试。'
+
+const UPSTREAM_ABORT_REASON = '上游响应在传输中途中断。'
+
+interface GatewayEntry {
+ id: string
+ kind: RemoteGatewayEntryKind
+ upstream: URL
+ authority: string
+ host: string
+ port: number
+ listening: boolean
+ connections: number
+ server: Server | undefined
+ sockets: Set<Duplex>
+ upstreamSockets: Set<Duplex>
+ requests: Set<ClientRequest>
+ tokenProvider: RemoteGatewayTokenProvider | undefined
+ auth: (() => RemoteAuthPolicy) | undefined
+ publicHost: (() => string | undefined) | undefined
+}
+
+interface ForwardAttempt {
+ /** 本次请求是否带着 DSH 原生 cookie 发往上游;为 false 时 401 只透传,不重铸。 */
+ credential: boolean
+ retryable: boolean
+}
+
+const entries = new Map<string, GatewayEntry>()
+
+const usedPorts = new Set<number>()
+
+const mintedCookies = new Map<string, string>()
+
+const mintedInFlight = new Map<string, Promise<string | undefined>>()
+
+const authFailures = new Map<string, RemoteAuthFailureRecord>()
+
+const subscribers = new Set<(event: RemoteGatewayEvent) => void>()
+
+let eventSeq = 0
+
+export const gateway = defineService({
+ async start(options: RemoteGatewayStartOptions): Promise<RemoteGatewayEntryStatus> {
+ return await startEntry(options)
+ },
+
+ async stop(id: string): Promise<void> {
+ await stopEntry(id)
+ },
+
+ status(id: string): RemoteGatewayEntryStatus | undefined {
+ const entry = entries.get(id)
+ return entry === undefined ? undefined : entryStatus(entry)
+ },
+
+ list(): RemoteGatewayEntryStatus[] {
+ return [...entries.values()].map(entryStatus)
+ },
+
+ subscribe(listener: (event: RemoteGatewayEvent) => void): () => void {
+ subscribers.add(listener)
+ return () => {
+ subscribers.delete(listener)
+ }
+ },
+
+ async dispose(): Promise<void> {
+ for (const id of [...entries.keys()])
+ await stopEntry(id)
+ entries.clear()
+ usedPorts.clear()
+ mintedCookies.clear()
+ mintedInFlight.clear()
+ authFailures.clear()
+ subscribers.clear()
+ },
+})
+
+// --- internal ---
+async function startEntry(options: RemoteGatewayStartOptions): Promise<RemoteGatewayEntryStatus> {
+ await stopEntry(options.id)
+ const upstream = new URL(options.upstream)
+ if (upstream.protocol !== 'http:')
+ throw new TypeError(`网关上游必须是 http URL:${options.upstream}`)
+ const host = options.kind === 'inbound' ? options.host ?? LOOPBACK : LOOPBACK
+ const entry: GatewayEntry = {
+ id: options.id,
+ kind: options.kind,
+ upstream,
+ authority: authorityFor(options.kind, upstream, options.port),
+ host,
+ port: 0,
+ listening: false,
+ connections: 0,
+ server: undefined,
+ sockets: new Set(),
+ upstreamSockets: new Set(),
+ requests: new Set(),
+ tokenProvider: options.tokenProvider,
+ auth: options.auth,
+ publicHost: options.publicHost,
+ }
+ entries.set(entry.id, entry)
+ try {
+ const binding = await bindEntry(entry, options.port)
+ entry.server = binding.server
+ entry.port = binding.port
+ entry.listening = true
+ usedPorts.add(binding.port)
+ }
+ catch (error) {
+ entry.listening = false
+ entry.port = 0
+ throw error
+ }
+ if (options.port !== 0 && entry.port !== options.port)
+ emit(entry, 'port', `首选端口 ${options.port} 不可用,已回落到 ${entry.port}`)
+ emit(entry, 'listening', `网关入口已监听 ${entryUrlOf(entry.host, entry.port)},上游 ${options.upstream}`)
+ return entryStatus(entry)
+}
+
+async function stopEntry(id: string): Promise<void> {
+ const entry = entries.get(id)
+ if (entry === undefined)
+ return
+ const wasListening = entry.listening
+ const stoppedPort = entry.port
+ const stoppedAuthority = entry.authority
+ entry.listening = false
+ entry.connections = 0
+ if (stoppedPort !== 0)
+ usedPorts.delete(stoppedPort)
+ mintedCookies.delete(stoppedAuthority)
+ mintedInFlight.delete(stoppedAuthority)
+ entry.port = 0
+ for (const request of entry.requests)
+ request.destroy()
+ entry.requests.clear()
+ for (const socket of entry.upstreamSockets)
+ socket.destroy()
+ entry.upstreamSockets.clear()
+ const server = entry.server
+ entry.server = undefined
+ if (server !== undefined) {
+ const closed = new Promise<void>((resolve) => {
+ server.close(() => resolve())
+ })
+ for (const socket of [...entry.sockets])
+ socket.destroy()
+ await closed
+ }
+ entry.sockets.clear()
+ if (wasListening)
+ emit(entry, 'stopped', `网关入口已停止 ${entryUrlOf(entry.host, stoppedPort)}`)
+}
+
+function entryStatus(entry: GatewayEntry): RemoteGatewayEntryStatus {
+ return {
+ id: entry.id,
+ kind: entry.kind,
+ state: entry.listening ? 'listening' : 'stopped',
+ host: entry.host,
+ port: entry.port,
+ url: entry.listening ? entryUrlOf(entry.host, entry.port) : '',
+ upstream: entry.upstream.origin,
+ connections: entry.connections,
+ }
+}
+
+async function bindEntry(entry: GatewayEntry, preferred: number): Promise<{ server: Server, port: number }> {
+ let lastError: unknown
+ for (let offset = 0; offset <= PORT_FALLBACK_LIMIT; offset++) {
+ const candidate = preferred + offset
+ if (candidate > 65535 || usedPorts.has(candidate))
+ continue
+ entry.port = candidate
+ entry.authority = authorityFor(entry.kind, entry.upstream, candidate)
+ try {
+ const server = await listenAt(entry, candidate)
+ const address = server.address()
+ const bound = typeof address === 'object' && address !== null ? address.port : candidate
+ entry.port = bound
+ entry.authority = authorityFor(entry.kind, entry.upstream, bound)
+ return { server, port: bound }
+ }
+ catch (error) {
+ lastError = error
+ if (codeOf(error) !== 'EADDRINUSE')
+ throw error
+ }
+ }
+ const error = new Error(`网关端口全部占用:已尝试 ${preferred}-${Math.min(preferred + PORT_FALLBACK_LIMIT, 65535)}${lastError === undefined ? '' : `(${messageOf(lastError)})`}`) as NodeJS.ErrnoException
+ error.code = PORTS_EXHAUSTED_CODE
+ throw error
+}
+
+function listenAt(entry: GatewayEntry, port: number): Promise<Server> {
+ return new Promise((resolve, reject) => {
+ const server = createServer((request, response) => {
+ void handleRequest(entry, request, response)
+ })
+ server.on('upgrade', (request, socket, head) => {
+ void handleUpgrade(entry, request, socket, head)
+ })
+ server.on('connection', (socket) => {
+ entry.sockets.add(socket)
+ entry.connections += 1
+ socket.on('close', () => {
+ entry.sockets.delete(socket)
+ entry.connections = Math.max(0, entry.connections - 1)
+ })
+ })
+ const onError = (error: Error) => {
+ reject(error)
+ }
+ server.once('error', onError)
+ server.listen(port, entry.host, () => {
+ server.off('error', onError)
+ server.on('error', (error) => {
+ emit(entry, 'upstream', `网关入口监听错误:${messageOf(error)}`)
+ })
+ resolve(server)
+ })
+ })
+}
+
+function handleRequest(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse): Promise<void> {
+ return dispatchRequest(entry, request, response).catch((error) => {
+ writeGatewayError(entry, response, 500, `网关请求处理失败:${messageOf(error)}`)
+ })
+}
+
+async function dispatchRequest(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse): Promise<void> {
+ if (isCrossSiteRequest(entry.kind, request.headers, entry.publicHost?.())) {
+ writeDenied(request, response, CROSS_SITE_REASON)
+ emit(entry, 'source', `已拦下跨站来源请求:${request.method ?? 'GET'} ${request.url ?? '/'}`)
+ return
+ }
+ const session = ensureSourceSession()
+ const source = sourceOf(entry, request, session)
+ const policy = entry.auth?.()
+ const decision = decideSourceAccess(source, policy)
+ if (decision === 'deny') {
+ writeDenied(request, response, denyReasonOf(policy))
+ return
+ }
+ const url = new URL(request.url ?? '/', 'http://gateway.invalid')
+ const exchange = entry.kind !== 'outbound' && source !== 'loopback' && isAuthConfigured(policy) && url.pathname === '/' && ((request.method === 'GET' && url.searchParams.has(AUTH_QUERY)) || isLoginSubmission(request))
+ if (decision === 'authenticate' || exchange) {
+ if (policy === undefined || !await admitAuthenticated(entry, request, response, source, policy))
+ return
+ }
+ await forward(entry, request, response, source, session)
+}
+
+/** 隧道入口的物理对端恒为回环,来源分类恒为 tunnel:不得采信任何请求头,否则 §7.2 门禁可被自报头绕过(S2 §7.1、§9)。 */
+function sourceOf(entry: GatewayEntry, request: IncomingMessage, session: string): RemoteSourceClass {
+ return entry.kind === 'tunnel' ? 'tunnel' : classifySource(request.headers, request.socket.remoteAddress, session)
+}
+
+function denyReasonOf(policy: RemoteAuthPolicy | undefined): string {
+ return isAuthStorageBroken(policy) ? BROKEN_AUTH_REASON : DENIED_REASON
+}
+
+async function admitAuthenticated(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse, source: RemoteSourceClass, policy: RemoteAuthPolicy): Promise<boolean> {
+ const now = Date.now()
+ const bucket = rateLimitKeyOf(source, request.socket.remoteAddress, entry.kind === 'tunnel' ? tunnelClientIpOf(request.headers) : undefined)
+ if (verifySession(parseCookieHeader(cookieHeaderOf(request.headers.cookie)).get(SESSION_COOKIE), policy.sessionSecret, now))
+ return true
+ const banned = rateLimitBlockedMs(authFailures.get(bucket), now)
+ if (banned > 0) {
+ writeAuthChallenge(request, response, BANNED_REASON, 429, banned)
+ return false
+ }
+ const url = new URL(request.url ?? '/', 'http://gateway.invalid')
+ if (request.method === 'GET' && url.pathname === '/' && url.searchParams.has(AUTH_QUERY)) {
+ const provided = url.searchParams.get(AUTH_QUERY) ?? undefined
+ if (tokenMatches(provided, policy.linkToken) || (provided !== undefined && (policy.consumePairingCode?.(provided) ?? tokenMatches(provided, policy.pairingCode ?? null)))) {
+ authFailures.delete(bucket)
+ writeSessionRedirect(response, policy, url.pathname, now)
+ return false
+ }
+ failAuth(bucket, now, request, response, '链接已失效,请输入访问密码。')
+ return false
+ }
+ if (isLoginSubmission(request)) {
+ const submitted = parseFormField(await readFormBody(request), LOGIN_FIELD)
+ const latest = entry.auth?.()
+ const completedAt = Date.now()
+ if (submitted !== undefined && isAuthConfigured(latest) && (verifyPassword(submitted, latest.password) || tokenMatches(submitted, latest.linkToken) || (latest.consumePairingCode?.(submitted) ?? tokenMatches(submitted, latest.pairingCode ?? null)))) {
+ authFailures.delete(bucket)
+ writeSessionRedirect(response, latest, `${url.pathname}${url.search}`, completedAt)
+ return false
+ }
+ failAuth(bucket, completedAt, request, response, '密码不正确。')
+ return false
+ }
+ writeAuthChallenge(request, response, undefined, 401, 0)
+ return false
+}
+
+/** 登录表单是导航形态的 urlencoded POST:API 客户端带 password 字段的 POST 不得被当成登录(S2 §7.3)。 */
+function isLoginSubmission(request: IncomingMessage): boolean {
+ if (request.method !== 'POST' || !isNavigationRequest(request.headers))
+ return false
+ return headerText(request.headers['content-type'])?.toLowerCase().startsWith('application/x-www-form-urlencoded') === true
+}
+
+function failAuth(bucket: string, now: number, request: IncomingMessage, response: ServerResponse, reason: string): void {
+ const record = rateLimitAfterFailure(authFailures.get(bucket), now)
+ authFailures.set(bucket, record)
+ const remaining = rateLimitBlockedMs(record, now)
+ writeAuthChallenge(
+ request,
+ response,
+ remaining > 0 ? `${BANNED_REASON}(剩余 ${Math.ceil(remaining / 1000)} 秒)` : reason,
+ remaining > 0 ? 429 : 401,
+ remaining,
+ )
+}
+
+function writeAuthChallenge(request: IncomingMessage, response: ServerResponse, message: string | undefined, status: number, retryAfterMs: number): void {
+ const text = message ?? '需要认证后才能访问。'
+ if (!isNavigationRequest(request.headers)) {
+ writeJson(response, status, text, retryAfterMs)
+ return
+ }
+ const html = loginPageHtml(message)
+ response.writeHead(status, {
+ 'content-type': 'text/html; charset=utf-8',
+ 'content-length': String(Buffer.byteLength(html)),
+ 'cache-control': 'no-store',
+ 'referrer-policy': 'no-referrer',
+ ...retryAfterMs > 0 ? { 'retry-after': String(Math.ceil(retryAfterMs / 1000)) } : {},
+ })
+ response.end(html)
+}
+
+function writeSessionRedirect(response: ServerResponse, policy: RemoteAuthPolicy, target: string, now: number): void {
+ const ticket = signSession(policy.sessionSecret, now)
+ response.writeHead(302, {
+ 'location': target,
+ 'set-cookie': sessionCookieOf(ticket, now),
+ 'cache-control': 'no-store',
+ 'referrer-policy': 'no-referrer',
+ })
+ response.end()
+}
+
+function sessionCookieOf(ticket: RemoteSessionTicket, now: number): string {
+ const maxAge = Math.max(0, Math.floor((ticket.expiresAt - now) / 1000))
+ return `${SESSION_COOKIE}=${ticket.value}; Max-Age=${maxAge}; Path=/; HttpOnly; SameSite=Lax`
+}
+
+function writeDenied(request: IncomingMessage, response: ServerResponse, reason: string): void {
+ if (!isNavigationRequest(request.headers)) {
+ writeJson(response, 403, reason, 0)
+ return
+ }
+ const html = deniedHtml(reason)
+ response.writeHead(403, {
+ 'content-type': 'text/html; charset=utf-8',
+ 'content-length': String(Buffer.byteLength(html)),
+ 'cache-control': 'no-store',
+ })
+ response.end(html)
+}
+
+function writeJson(response: ServerResponse, status: number, message: string, retryAfterMs: number): void {
+ const body = JSON.stringify({ error: message })
+ response.writeHead(status, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'content-length': String(Buffer.byteLength(body)),
+ 'cache-control': 'no-store',
+ ...retryAfterMs > 0 ? { 'retry-after': String(Math.ceil(retryAfterMs / 1000)) } : {},
+ })
+ response.end(body)
+}
+
+async function forward(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse, source: RemoteSourceClass, session: string): Promise<void> {
+ const inject = entry.kind !== 'outbound'
+ const headers = forwardHeadersOf(request.headers, {
+ authority: entry.authority,
+ upgrade: isUpgradeOf(request.headers),
+ ...inject ? { source, session } : { source: 'public', session: 'outbound' },
+ ...entry.kind === 'outbound' ? { identity: true } : {},
+ })
+ const cookie = await ensureMintedCookie(entry)
+ if (cookie !== undefined)
+ headers.cookie = mergeCookieHeader(cookieHeaderOf(headers.cookie), [cookie])
+ await sendUpstream(entry, request, response, headers, { retryable: true, credential: cookie !== undefined }, source)
+}
+
+function sendUpstream(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse, headers: OutgoingHttpHeaders, attempt: ForwardAttempt, source: RemoteSourceClass): Promise<void> {
+ return new Promise((resolve) => {
+ const upstream = httpRequest({
+ host: entry.upstream.hostname,
+ port: upstreamPortOf(entry.upstream),
+ method: request.method,
+ path: request.url ?? '/',
+ headers,
+ agent: false,
+ })
+ entry.requests.add(upstream)
+ let timedOut = false
+ const timer = setTimeout(() => {
+ timedOut = true
+ upstream.destroy()
+ }, isWriteClass(request.method) ? LONG_TIMEOUT_MS : SHORT_TIMEOUT_MS)
+ upstream.on('response', (upstreamResponse) => {
+ clearTimeout(timer)
+ entry.requests.delete(upstream)
+ void respondUpstream(entry, request, response, upstreamResponse, headers, attempt, source)
+ .catch((error) => {
+ writeGatewayError(entry, response, 500, `网关响应处理失败:${messageOf(error)}`)
+ })
+ .finally(resolve)
+ })
+ upstream.on('error', (error) => {
+ clearTimeout(timer)
+ entry.requests.delete(upstream)
+ const reason = timedOut
+ ? timeoutReasonOf(entry)
+ : `上游不可达:${entry.upstream.origin}(${codeOf(error) ?? messageOf(error)})`
+ writeGatewayError(entry, response, timedOut ? 504 : 502, reason)
+ resolve()
+ })
+ request.pipe(upstream)
+ })
+}
+
+async function respondUpstream(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse, upstreamResponse: IncomingMessage, headers: OutgoingHttpHeaders, attempt: ForwardAttempt, source: RemoteSourceClass): Promise<void> {
+ if (upstreamResponse.statusCode === 401 && attempt.retryable && attempt.credential && entry.tokenProvider !== undefined && isReplayable(request.headers)) {
+ upstreamResponse.pause()
+ mintedCookies.delete(entry.authority)
+ const cookie = await mintCookie(entry)
+ if (cookie !== undefined) {
+ upstreamResponse.destroy()
+ const retried = { ...headers, cookie: mergeCookieHeader(cookieHeaderOf(headers.cookie), [cookie]) }
+ await sendUpstream(entry, request, response, retried, { retryable: false, credential: true }, source)
+ return
+ }
+ upstreamResponse.resume()
+ }
+ writeUpstreamBody(entry, request, response, upstreamResponse, source)
+}
+
+function writeUpstreamBody(entry: GatewayEntry, request: IncomingMessage, response: ServerResponse, upstreamResponse: IncomingMessage, source: RemoteSourceClass): void {
+ const plan = responsePlanOf({
+ acceptEncoding: headerText(request.headers['accept-encoding']),
+ contentType: headerText(upstreamResponse.headers['content-type']),
+ contentLength: contentLengthOf(upstreamResponse.headers['content-length']),
+ upstreamEncoding: headerText(upstreamResponse.headers['content-encoding']),
+ supportsZstd: supportsZstd(),
+ compress: source !== 'loopback',
+ minBytes: COMPRESS_MIN_BYTES,
+ })
+ const headers = responseHeadersOf(upstreamResponse.headers)
+ if (entry.kind !== 'outbound')
+ delete headers['set-cookie']
+ const status = upstreamResponse.statusCode ?? 200
+ const decompressor = plan.decode === undefined ? undefined : createDecompressor(plan.decode)
+ const coding = plan.coding !== undefined && (plan.decode === undefined || decompressor !== undefined) ? plan.coding : undefined
+ if (source !== 'loopback')
+ appendVary(headers)
+ if (coding === undefined) {
+ if (decompressor === undefined) {
+ pipeThrough(entry, upstreamResponse, response, status, headers, undefined)
+ return
+ }
+ delete headers['content-encoding']
+ delete headers['content-length']
+ pipeThrough(entry, upstreamResponse, response, status, headers, decompressor)
+ return
+ }
+ delete headers['content-length']
+ delete headers['content-encoding']
+ headers['content-encoding'] = coding
+ if (!plan.buffered) {
+ pipeThrough(entry, upstreamResponse, response, status, headers, decompressor, createCompressor(coding, plan.streaming))
+ return
+ }
+ pipeBuffered(entry, upstreamResponse, response, status, headers, coding)
+}
+
+function pipeThrough(entry: GatewayEntry, upstreamResponse: IncomingMessage, response: ServerResponse, status: number, headers: OutgoingHttpHeaders, decompressor?: Transform, compressor?: Transform): void {
+ response.writeHead(status, headers)
+ const stages: (Readable | Writable)[] = [upstreamResponse]
+ if (decompressor !== undefined)
+ stages.push(decompressor)
+ if (compressor !== undefined)
+ stages.push(compressor)
+ stages.push(response)
+ pipeline(stages, (error) => {
+ if (error != null && (!upstreamResponse.complete || codeOf(error) !== 'ERR_STREAM_PREMATURE_CLOSE'))
+ emit(entry, 'compression', `响应流中断:${messageOf(error)}(${entry.upstream.origin})`)
+ })
+}
+
+function pipeBuffered(entry: GatewayEntry, upstreamResponse: IncomingMessage, response: ServerResponse, status: number, headers: OutgoingHttpHeaders, coding: 'zstd' | 'gzip'): void {
+ const chunks: Buffer[] = []
+ let total = 0
+ let decided = false
+ let compressor: Transform | undefined
+
+ function onData(chunk: Buffer): void {
+ chunks.push(chunk)
+ total += chunk.length
+ if (total >= COMPRESS_MIN_BYTES)
+ decide(true)
+ }
+
+ function decide(compress: boolean): void {
+ if (decided)
+ return
+ decided = true
+ upstreamResponse.off('data', onData)
+ upstreamResponse.pause()
+ if (!compress) {
+ delete headers['content-encoding']
+ headers['content-length'] = String(total)
+ response.writeHead(status, headers)
+ for (const chunk of chunks)
+ response.write(chunk)
+ upstreamResponse.pipe(response)
+ }
+ else {
+ response.writeHead(status, headers)
+ compressor = createCompressor(coding, false)
+ compressor.pipe(response)
+ for (const chunk of chunks)
+ compressor.write(chunk)
+ upstreamResponse.pipe(compressor)
+ }
+ upstreamResponse.resume()
+ }
+
+ function fail(error: unknown): void {
+ const reason = messageOf(error)
+ if (!decided) {
+ decided = true
+ upstreamResponse.off('data', onData)
+ upstreamResponse.destroy()
+ emit(entry, 'compression', `上游响应流错误,已终止该响应:${entry.upstream.origin}(${reason})`)
+ if (!response.headersSent)
+ writeJson(response, 502, `${UPSTREAM_ABORT_REASON}(${entry.upstream.origin})`, 0)
+ return
+ }
+ emit(entry, 'compression', `上游响应流错误,已中止压缩响应:${reason}`)
+ compressor?.destroy()
+ response.destroy()
+ }
+
+ upstreamResponse.on('data', onData)
+ upstreamResponse.on('end', () => {
+ decide(false)
+ })
+ upstreamResponse.on('error', fail)
+ response.on('close', () => {
+ if (!decided) {
+ decided = true
+ upstreamResponse.destroy()
+ }
+ })
+}
+
+function handleUpgrade(entry: GatewayEntry, request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> {
+ return dispatchUpgrade(entry, request, socket, head).catch(() => {
+ rejectUpgrade(socket, 500, '网关升级处理失败。')
+ })
+}
+async function dispatchUpgrade(entry: GatewayEntry, request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> {
+ if (isCrossSiteRequest(entry.kind, request.headers, entry.publicHost?.())) {
+ emit(entry, 'source', '已拦下跨站来源的 WebSocket 握手')
+ rejectUpgrade(socket, 403, CROSS_SITE_REASON)
+ return
+ }
+ const session = ensureSourceSession()
+ const source = sourceOf(entry, request, session)
+ const policy = entry.auth?.()
+ const decision = decideSourceAccess(source, policy)
+ const admitted = decision === 'allow'
+ || (decision === 'authenticate' && policy !== undefined && verifySession(parseCookieHeader(cookieHeaderOf(request.headers.cookie)).get(SESSION_COOKIE), policy.sessionSecret, Date.now()))
+ if (!admitted) {
+ rejectUpgrade(socket, decision === 'deny' ? 403 : 401, decision === 'deny' ? denyReasonOf(policy) : '需要认证后才能访问。')
+ return
+ }
+ const inject = entry.kind !== 'outbound'
+ const headers = forwardHeadersOf(request.headers, {
+ authority: entry.authority,
+ upgrade: true,
+ ...inject ? { source, session } : { source: 'public', session: 'outbound' },
+ ...entry.kind === 'outbound' ? { identity: true } : {},
+ })
+ const release = guardUpgradeSocket(socket)
+ let cookie: string | undefined
+ try {
+ cookie = await ensureMintedCookie(entry)
+ }
+ finally {
+ release()
+ }
+ if (socket.destroyed)
+ return
+ if (cookie !== undefined)
+ headers.cookie = mergeCookieHeader(cookieHeaderOf(headers.cookie), [cookie])
+ openUpgrade(entry, request, socket, head, headers, { retryable: true, credential: cookie !== undefined })
+}
+
+/**
+ * 铸造窗口的活性守卫:冷缓存下 `ensureMintedCookie` 会 await 到远端 token,期间客户端可能已经断开,
+ * 而 `openUpgrade` 的 end/close 监听要到铸造之后才注册——两个事件都已错过,之后仍会向上游完成 101
+ * 却再没有代码销毁下游 socket,半开 fd 与 §10 的活跃连接数一起泄漏。守卫必须早于 await 注册,
+ * 断开时直接销毁 socket,`socket.destroyed` 即铸造之后判定是否还要向上游拨号的依据。
+ */
+function guardUpgradeSocket(socket: Duplex): () => void {
+ const close = (): void => {
+ socket.destroy()
+ }
+ socket.on('close', close)
+ socket.on('end', close)
+ return () => {
+ socket.off('close', close)
+ socket.off('end', close)
+ }
+}
+
+/** 升级被拒或超时:网关自行组帧(content-length 与正文一致),不复制上游的逐跳头。 */
+function rejectUpgrade(socket: Duplex, status: number, message: string): void {
+ const body = JSON.stringify({ error: message })
+ socket.end(`HTTP/1.1 ${status} ${statusTextOf(status)}\r\ncontent-type: application/json; charset=utf-8\r\ncontent-length: ${Buffer.byteLength(body)}\r\nconnection: close\r\n\r\n${body}`)
+}
+
+/** 非 101 的上游响应已经过分块解码,转发时必须剥掉逐跳头、按真实长度重新组帧并显式收束连接(S2 §8.4)。 */
+function rejectFromUpstream(entry: GatewayEntry, socket: Duplex, upstreamResponse: IncomingMessage): void {
+ const headers = responseHeadersOf(upstreamResponse.headers)
+ if (entry.kind !== 'outbound')
+ delete headers['set-cookie']
+ const declared = contentLengthOf(upstreamResponse.headers['content-length'])
+ delete headers['content-length']
+ headers.connection = 'close'
+ const head = [`HTTP/1.1 ${upstreamResponse.statusCode ?? 502} ${upstreamResponse.statusMessage ?? ''}`]
+ for (const [name, value] of Object.entries(headers)) {
+ for (const item of Array.isArray(value) ? value : [value])
+ head.push(`${name}: ${item ?? ''}`)
+ }
+ if (declared !== undefined)
+ head.push(`content-length: ${declared}`)
+ writeSocket(socket, `${head.join('\r\n')}\r\n\r\n`)
+ upstreamResponse.pipe(socket)
+}
+
+function upgradeHeadLines(entry: GatewayEntry, status: number, statusMessage: string, rawHeaders: string[]): string {
+ const lines = [`HTTP/1.1 ${status} ${statusMessage}`]
+ for (let index = 0; index < rawHeaders.length; index += 2) {
+ const name = rawHeaders[index] ?? ''
+ if (entry.kind !== 'outbound' && name.toLowerCase() === 'set-cookie')
+ continue
+ lines.push(`${name}: ${rawHeaders[index + 1] ?? ''}`)
+ }
+ return `${lines.join('\r\n')}\r\n\r\n`
+}
+
+function openUpgrade(entry: GatewayEntry, request: IncomingMessage, socket: Duplex, head: Buffer, headers: OutgoingHttpHeaders, attempt: ForwardAttempt): void {
+ const upstream = httpRequest({
+ host: entry.upstream.hostname,
+ port: upstreamPortOf(entry.upstream),
+ method: request.method,
+ path: request.url ?? '/',
+ headers,
+ agent: false,
+ })
+ entry.requests.add(upstream)
+ let live = true
+ let timer: NodeJS.Timeout
+ const settle = (): boolean => {
+ clearTimeout(timer)
+ entry.requests.delete(upstream)
+ socket.off('close', endUpgrade)
+ socket.off('end', endUpgrade)
+ const first = live
+ live = false
+ return first
+ }
+ /** 客户端在慢上游应答前断开时 socket 只报 'end' 不报 'close',两者都必须归位:否则定时器、fd 与上游请求无界累积。 */
+ function endUpgrade(): void {
+ settle()
+ socket.destroy()
+ upstream.destroy()
+ }
+ const timeout = (): void => {
+ settle()
+ rejectUpgrade(socket, 504, timeoutReasonOf(entry))
+ socket.destroy()
+ upstream.destroy()
+ }
+ timer = setTimeout(timeout, SHORT_TIMEOUT_MS)
+ socket.on('close', endUpgrade)
+ socket.on('end', endUpgrade)
+ upstream.on('upgrade', (upstreamResponse, upstreamSocket, upstreamHead) => {
+ if (!settle())
+ return
+ entry.upstreamSockets.add(upstreamSocket)
+ upstreamSocket.on('close', () => entry.upstreamSockets.delete(upstreamSocket))
+ writeSocket(socket, upgradeHeadLines(entry, upstreamResponse.statusCode ?? 101, upstreamResponse.statusMessage ?? 'Switching Protocols', upstreamResponse.rawHeaders))
+ if (upstreamHead.length > 0)
+ writeSocket(socket, upstreamHead)
+ upstreamSocket.on('error', () => upstreamSocket.destroy())
+ socket.pipe(upstreamSocket)
+ upstreamSocket.pipe(socket)
+ socket.on('end', () => upstreamSocket.destroy())
+ upstreamSocket.on('end', () => socket.destroy())
+ socket.on('close', () => upstreamSocket.destroy())
+ upstreamSocket.on('close', () => socket.destroy())
+ })
+ upstream.on('response', (upstreamResponse) => {
+ if (!settle())
+ return
+ if (upstreamResponse.statusCode === 401 && attempt.retryable && attempt.credential && entry.tokenProvider !== undefined) {
+ upstreamResponse.resume()
+ mintedCookies.delete(entry.authority)
+ const release = guardUpgradeSocket(socket)
+ void mintCookie(entry).then((cookie) => {
+ if (cookie === undefined) {
+ rejectUpgrade(socket, 401, '需要认证后才能访问。')
+ return
+ }
+ if (socket.destroyed)
+ return
+ openUpgrade(entry, request, socket, head, { ...headers, cookie: mergeCookieHeader(cookieHeaderOf(headers.cookie), [cookie]) }, { retryable: false, credential: true })
+ }).catch(() => {
+ rejectUpgrade(socket, 502, 'DSH 原生 cookie 重铸失败。')
+ }).finally(release)
+ return
+ }
+ rejectFromUpstream(entry, socket, upstreamResponse)
+ })
+ upstream.on('error', () => {
+ settle()
+ socket.destroy()
+ })
+ if (head.length > 0)
+ upstream.write(head)
+ request.pipe(upstream)
+}
+
+function statusTextOf(status: number): string {
+ switch (status) {
+ case 401:
+ return 'Unauthorized'
+ case 403:
+ return 'Forbidden'
+ case 502:
+ return 'Bad Gateway'
+ case 504:
+ return 'Gateway Timeout'
+ default:
+ return 'Internal Server Error'
+ }
+}
+
+function writeSocket(socket: Duplex, chunk: string | Buffer): void {
+ if (!socket.destroyed && socket.writable)
+ socket.write(chunk)
+}
+
+async function ensureMintedCookie(entry: GatewayEntry): Promise<string | undefined> {
+ const cached = mintedCookies.get(entry.authority)
+ if (cached !== undefined)
+ return cached
+ const pending = mintedInFlight.get(entry.authority)
+ if (pending !== undefined)
+ return await pending
+ const minted = mintCookie(entry)
+ mintedInFlight.set(entry.authority, minted)
+ try {
+ return await minted
+ }
+ finally {
+ mintedInFlight.delete(entry.authority)
+ }
+}
+
+async function mintCookie(entry: GatewayEntry): Promise<string | undefined> {
+ const provider = entry.tokenProvider
+ if (provider === undefined)
+ return undefined
+ let mintUrl: string | undefined
+ try {
+ mintUrl = await withTimeout(provider(entry.authority))
+ }
+ catch (error) {
+ emit(entry, 'cookie', `DSH 原生 cookie 铸造失败(token 不可用),已透传上游响应:${messageOf(error)}`)
+ return undefined
+ }
+ if (mintUrl === undefined) {
+ emit(entry, 'cookie', `DSH 原生 cookie 铸造失败(token 不可用),已透传上游响应(${entry.authority})`)
+ return undefined
+ }
+ const pairs = await requestMint(entry, mintUrl)
+ if (pairs.length === 0) {
+ emit(entry, 'cookie', `DSH 原生 cookie 铸造未取到会话 cookie,已透传上游响应(${entry.authority})`)
+ return undefined
+ }
+ const cookie = pairs.join('; ')
+ mintedCookies.set(entry.authority, cookie)
+ return cookie
+}
+
+function requestMint(entry: GatewayEntry, mintUrl: string): Promise<string[]> {
+ return new Promise((resolve) => {
+ let path: string
+ try {
+ const url = new URL(mintUrl)
+ path = `${url.pathname}${url.search}`
+ }
+ catch {
+ resolve([])
+ return
+ }
+ const request = httpRequest({
+ host: entry.upstream.hostname,
+ port: upstreamPortOf(entry.upstream),
+ method: 'GET',
+ path,
+ headers: { host: entry.authority, accept: 'text/html', connection: 'close' },
+ agent: false,
+ })
+ const timer = setTimeout(() => {
+ request.destroy()
+ }, MINT_TIMEOUT_MS)
+ request.on('response', (response) => {
+ clearTimeout(timer)
+ const pairs = cookiePairsOf(response.headers['set-cookie'])
+ response.resume()
+ resolve(pairs)
+ })
+ request.on('error', () => {
+ clearTimeout(timer)
+ resolve([])
+ })
+ request.end()
+ })
+}
+
+/** token provider 本身也必须限时:它一旦永不 settle,挂起的铸造链会一直持有 request、socket 与 head。 */
+function withTimeout(pending: Promise<string | undefined>): Promise<string | undefined> {
+ let timer: NodeJS.Timeout
+ const expiry = new Promise<undefined>((resolve) => {
+ timer = setTimeout(resolve, TOKEN_TIMEOUT_MS, undefined)
+ })
+ void pending.catch(() => undefined).finally(() => clearTimeout(timer))
+ return Promise.race([pending, expiry])
+}
+
+async function readFormBody(request: IncomingMessage): Promise<string> {
+ const chunks: Buffer[] = []
+ let total = 0
+ for await (const chunk of request) {
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
+ total += buffer.length
+ if (total > FORM_BODY_LIMIT)
+ return ''
+ chunks.push(buffer)
+ }
+ return Buffer.concat(chunks).toString('utf8')
+}
+
+function writeGatewayError(entry: GatewayEntry, response: ServerResponse, status: number, reason: string): void {
+ emit(entry, 'upstream', reason)
+ if (response.headersSent) {
+ response.destroy()
+ return
+ }
+ writeJson(response, status, reason, 0)
+}
+
+function appendVary(headers: OutgoingHttpHeaders): void {
+ const existing = headers.vary
+ const value = Array.isArray(existing) ? existing.join(', ') : typeof existing === 'string' ? existing : ''
+ const tokens = value.toLowerCase().split(',').map(token => token.trim())
+ if (!tokens.includes('accept-encoding'))
+ headers.vary = value === '' ? 'accept-encoding' : `${value}, accept-encoding`
+}
+
+function emit(entry: { id: string }, kind: RemoteGatewayEventKind, line: string): void {
+ eventSeq += 1
+ const event: RemoteGatewayEvent = { seq: eventSeq, ts: new Date().toISOString(), id: entry.id, kind, line }
+ for (const listener of [...subscribers]) {
+ try {
+ listener(event)
+ }
+ catch {
+ continue
+ }
+ }
+}
+
+function cookieHeaderOf(value: number | string | string[] | undefined): string | undefined {
+ if (Array.isArray(value))
+ return value.join('; ')
+ return value === undefined ? undefined : String(value)
+}
+
+function headerText(value: number | string | string[] | undefined): string | undefined {
+ if (Array.isArray(value))
+ return value[0]
+ return value === undefined ? undefined : String(value)
+}
+
+function contentLengthOf(value: number | string | string[] | undefined): number | undefined {
+ const text = headerText(value)
+ if (text === undefined)
+ return undefined
+ const parsed = Number(text)
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : undefined
+}
+
+function isWriteClass(method: string | undefined): boolean {
+ return method !== undefined && method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS'
+}
+
+function timeoutReasonOf(entry: GatewayEntry): string {
+ return `上游超时:${entry.upstream.origin}`
+}
+
+function codeOf(error: unknown): string | undefined {
+ if (typeof error !== 'object' || error === null)
+ return undefined
+ const code = (error as { code?: unknown }).code
+ return typeof code === 'string' ? code : undefined
+}
diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.types.ts b/packages/dsh-tauri-remote/src/host/service/gateway.types.ts
new file mode 100644
index 00000000..17f21aef
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/gateway.types.ts
@@ -0,0 +1,32 @@
+import type { RemoteSourceClass } from '../types/index'
+
+export type RemoteContentCoding = 'zstd' | 'gzip'
+
+/** 转发请求的改写与注入计划:authority 对齐 + 内部来源标识 + 出站腿的 identity 声明。 */
+export interface RemoteForwardPlan {
+ authority: string
+ source?: RemoteSourceClass
+ session?: string
+ identity?: boolean
+ upgrade?: boolean
+}
+
+/** 响应体处理计划:是否先解压、是否重压、是否逐块流式、是否按阈值缓冲决策(S2 §8.2/§8.3)。 */
+export interface RemoteResponsePlan {
+ decode?: string
+ coding?: RemoteContentCoding
+ streaming: boolean
+ buffered: boolean
+}
+
+export interface RemoteResponsePlanInput {
+ acceptEncoding: string | undefined
+ contentType: string | undefined
+ contentLength: number | undefined
+ upstreamEncoding: string | undefined
+ supportsZstd: boolean
+ /** 下游为物理回环时一律 identity(S2 §8.1 的「本地回环腿」)。 */
+ compress: boolean
+ /** 小于该体积不压缩;SSE 不受此限。 */
+ minBytes: number
+}
diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.utils.test.ts b/packages/dsh-tauri-remote/src/host/service/gateway.utils.test.ts
new file mode 100644
index 00000000..cb6b5cef
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/gateway.utils.test.ts
@@ -0,0 +1,419 @@
+import type { IncomingHttpHeaders } from 'node:http'
+import { Buffer } from 'node:buffer'
+import { Readable } from 'node:stream'
+import { pipeline } from 'node:stream/promises'
+import * as zlib from 'node:zlib'
+import { describe, expect, it } from 'vitest'
+import { GATEWAY_SESSION_HEADER, GATEWAY_SOURCE_HEADER } from '../config/constants'
+import { acceptsEncoding, authorityFor, cookiePairsOf, createCompressor, createDecompressor, entryUrlOf, forwardHeadersOf, isCompressible, isCrossSiteRequest, isEventStream, isNavigationRequest, isReplayable, isUpgradeOf, loginPageHtml, mergeCookieHeader, negotiateEncoding, parseCookieHeader, parseFormField, responseHeadersOf, responsePlanOf, supportsZstd, tunnelClientIpOf, upstreamPortOf } from './gateway.utils'
+
+const SESSION = 'gateway-session-token'
+
+async function roundTrip(coding: 'zstd' | 'gzip', streaming: boolean, payload: string): Promise<string> {
+ const compressor = createCompressor(coding, streaming)
+ const decompressor = createDecompressor(coding)
+ expect(decompressor).toBeDefined()
+ const compressed: Buffer[] = []
+ await pipeline(Readable.from([Buffer.from(payload)]), compressor, async function* (source) {
+ for await (const chunk of source)
+ compressed.push(chunk as Buffer)
+ })
+ const restored: Buffer[] = []
+ await pipeline(Readable.from(compressed), decompressor as NodeJS.ReadWriteStream, async function* (source) {
+ for await (const chunk of source)
+ restored.push(chunk as Buffer)
+ })
+ return Buffer.concat(restored).toString('utf8')
+}
+
+describe('authorityFor', () => {
+ it('uses the gateway loopback port for the outbound leg', () => {
+ expect(authorityFor('outbound', new URL('http://127.0.0.1:39001'), 3088)).toBe('127.0.0.1:3088')
+ })
+
+ it('uses the upstream authority for the inbound and tunnel legs', () => {
+ expect(authorityFor('inbound', new URL('http://127.0.0.1:3080'), 3088)).toBe('127.0.0.1:3080')
+ expect(authorityFor('tunnel', new URL('http://127.0.0.1:3080'), 3088)).toBe('127.0.0.1:3080')
+ expect(authorityFor('inbound', new URL('http://[::1]:3080'), 3088)).toBe('[::1]:3080')
+ })
+})
+
+describe('entryUrlOf / upstreamPortOf', () => {
+ it('builds the entry URL with the real port and brackets IPv6 hosts', () => {
+ expect(entryUrlOf('127.0.0.1', 3088)).toBe('http://127.0.0.1:3088')
+ expect(entryUrlOf('0.0.0.0', 3089)).toBe('http://0.0.0.0:3089')
+ expect(entryUrlOf('fd00::1', 3088)).toBe('http://[fd00::1]:3088')
+ })
+
+ it('defaults an upstream URL without an explicit port to 80', () => {
+ expect(upstreamPortOf(new URL('http://127.0.0.1:39001'))).toBe(39001)
+ expect(upstreamPortOf(new URL('http://127.0.0.1'))).toBe(80)
+ })
+})
+
+describe('forwardHeadersOf', () => {
+ const headers: IncomingHttpHeaders = {
+ 'host': '192.168.1.5:3088',
+ 'origin': 'http://192.168.1.5:3088',
+ 'cookie': 'browser=1',
+ 'accept': 'text/html',
+ 'connection': 'keep-alive',
+ 'x-forwarded-for': '203.0.113.7',
+ }
+
+ it('rewrites Host and Origin to the forwarding authority', () => {
+ const out = forwardHeadersOf(headers, { authority: '127.0.0.1:3080' })
+ expect(out.host).toBe('127.0.0.1:3080')
+ expect(out.origin).toBe('http://127.0.0.1:3080')
+ })
+
+ it('leaves an absent Origin absent', () => {
+ const out = forwardHeadersOf({ host: '127.0.0.1:3088' }, { authority: '127.0.0.1:3080' })
+ expect(out.origin).toBeUndefined()
+ })
+
+ it('drops hop-by-hop headers on the plain path and keeps them on the upgrade path', () => {
+ expect(forwardHeadersOf(headers, { authority: '127.0.0.1:3080' }).connection).toBeUndefined()
+ const upgrade = forwardHeadersOf({ ...headers, upgrade: 'websocket', connection: 'Upgrade' }, { authority: '127.0.0.1:3080', upgrade: true })
+ expect(upgrade.connection).toBe('Upgrade')
+ expect(upgrade.upgrade).toBe('websocket')
+ })
+
+ it('injects both internal markers on the forwarding legs', () => {
+ const out = forwardHeadersOf(headers, { authority: '127.0.0.1:3080', source: 'private', session: SESSION })
+ expect(out[GATEWAY_SOURCE_HEADER]).toBe('private')
+ expect(out[GATEWAY_SESSION_HEADER]).toBe(SESSION)
+ })
+
+ it('replaces client-supplied markers instead of appending to them', () => {
+ const forged: IncomingHttpHeaders = { ...headers, [GATEWAY_SOURCE_HEADER]: 'loopback', [GATEWAY_SESSION_HEADER]: 'forged' }
+ const out = forwardHeadersOf(forged, { authority: '127.0.0.1:3080', source: 'public', session: SESSION })
+ expect(out[GATEWAY_SOURCE_HEADER]).toBe('public')
+ expect(out[GATEWAY_SESSION_HEADER]).toBe(SESSION)
+ const multi = forwardHeadersOf({ ...forged, [GATEWAY_SOURCE_HEADER]: ['loopback', 'private'] }, { authority: '127.0.0.1:3080', source: 'public', session: SESSION })
+ expect(multi[GATEWAY_SOURCE_HEADER]).toBe('public')
+ })
+
+ it.each([false, true])('replaces forged markers with outbound denial markers (upgrade=%s) without the local secret', (upgrade) => {
+ const forged: IncomingHttpHeaders = {
+ ...headers,
+ ...(upgrade ? { connection: 'Upgrade', upgrade: 'websocket' } : {}),
+ [GATEWAY_SOURCE_HEADER]: ['loopback', 'private'],
+ [GATEWAY_SESSION_HEADER]: [SESSION, SESSION],
+ }
+ const out = forwardHeadersOf(forged, { authority: '127.0.0.1:3088', source: 'public', session: 'outbound', upgrade, identity: true })
+ expect(out[GATEWAY_SOURCE_HEADER]).toBe('public')
+ expect(out[GATEWAY_SESSION_HEADER]).toBe('outbound')
+ expect(out['accept-encoding']).toBe('identity')
+ expect(JSON.stringify(out)).not.toContain(SESSION)
+ })
+
+ it('重新宣告正文分帧:上游只声明了 transfer-encoding 时改写为分块,绝不留下无分帧的裸正文', () => {
+ const chunked = forwardHeadersOf({ 'host': '127.0.0.1:3088', 'transfer-encoding': 'chunked' }, { authority: '127.0.0.1:3080' })
+ expect(chunked['transfer-encoding']).toBe('chunked')
+ expect(chunked['content-length']).toBeUndefined()
+ })
+
+ it('正文长度已知时保留 content-length,不额外声明分块', () => {
+ const sized = forwardHeadersOf({ 'host': '127.0.0.1:3088', 'content-length': '12' }, { authority: '127.0.0.1:3080' })
+ expect(sized['content-length']).toBe(12)
+ expect(sized['transfer-encoding']).toBeUndefined()
+ const empty = forwardHeadersOf({ 'host': '127.0.0.1:3088', 'content-length': '0' }, { authority: '127.0.0.1:3080' })
+ expect(empty['content-length']).toBe(0)
+ expect(empty['transfer-encoding']).toBeUndefined()
+ })
+
+ it('无正文声明的请求不凭空添上分块,升级路径原样透传分帧头', () => {
+ const plain = forwardHeadersOf({ host: '127.0.0.1:3088' }, { authority: '127.0.0.1:3080' })
+ expect(plain['transfer-encoding']).toBeUndefined()
+ expect(plain['content-length']).toBeUndefined()
+ const upgrade = forwardHeadersOf({ 'host': '127.0.0.1:3088', 'transfer-encoding': 'chunked' }, { authority: '127.0.0.1:3080', upgrade: true })
+ expect(upgrade['transfer-encoding']).toBe('chunked')
+ })
+})
+
+describe('responseHeadersOf', () => {
+ it('keeps end-to-end headers and drops hop-by-hop ones', () => {
+ const out = responseHeadersOf({ 'content-type': 'text/plain', 'content-length': '12', 'connection': 'keep-alive', 'transfer-encoding': 'chunked', 'set-cookie': ['a=1'] })
+ expect(out).toEqual({ 'content-type': 'text/plain', 'content-length': '12', 'set-cookie': ['a=1'] })
+ })
+})
+
+describe('request shape predicates', () => {
+ it('detects an upgrade request through either marker', () => {
+ expect(isUpgradeOf({ upgrade: 'websocket' })).toBe(true)
+ expect(isUpgradeOf({ connection: 'keep-alive, Upgrade' })).toBe(true)
+ expect(isUpgradeOf({ connection: 'keep-alive' })).toBe(false)
+ expect(isUpgradeOf({})).toBe(false)
+ })
+
+ it('detects a navigation request by its Accept header', () => {
+ expect(isNavigationRequest({ accept: 'text/html,application/xhtml+xml' })).toBe(true)
+ expect(isNavigationRequest({ accept: '*/*' })).toBe(false)
+ expect(isNavigationRequest({})).toBe(false)
+ })
+
+ it('treats only body-less requests as replayable', () => {
+ expect(isReplayable({})).toBe(true)
+ expect(isReplayable({ 'content-length': '0' })).toBe(true)
+ expect(isReplayable({ 'content-length': '10' })).toBe(false)
+ expect(isReplayable({ 'transfer-encoding': 'chunked' })).toBe(false)
+ })
+
+ it('flags cross-site initiators by Sec-Fetch-Site or by an Origin outside the request authority', () => {
+ expect(isCrossSiteRequest('inbound', { 'host': '127.0.0.1:3088', 'sec-fetch-site': 'cross-site' })).toBe(true)
+ expect(isCrossSiteRequest('inbound', { host: '127.0.0.1:3088', origin: 'https://evil.example' })).toBe(true)
+ expect(isCrossSiteRequest('inbound', { host: '127.0.0.1:3088', origin: 'null' })).toBe(true)
+ expect(isCrossSiteRequest('inbound', { host: '127.0.0.1:3088', origin: 'http://127.0.0.1:3089' })).toBe(true)
+ expect(isCrossSiteRequest('inbound', { 'host': '127.0.0.1:3088', 'origin': 'http://127.0.0.1:3088', 'sec-fetch-site': 'same-origin' })).toBe(false)
+ expect(isCrossSiteRequest('inbound', { 'host': '127.0.0.1:3088', 'sec-fetch-site': 'none' })).toBe(false)
+ expect(isCrossSiteRequest('inbound', { 'host': 's2.trycloudflare.com', 'origin': 'https://s2.trycloudflare.com', 'sec-fetch-site': 'same-origin' })).toBe(false)
+ expect(isCrossSiteRequest('inbound', { host: 's2.trycloudflare.com', origin: 'http://127.0.0.1:3088' })).toBe(true)
+ expect(isCrossSiteRequest('inbound', { 'host': '127.0.0.1:3088', 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'no-cors' })).toBe(true)
+ expect(isCrossSiteRequest('inbound', { 'host': '127.0.0.1:3088', 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'websocket' })).toBe(true)
+ expect(isCrossSiteRequest('inbound', { 'host': '127.0.0.1:3088', 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'navigate' })).toBe(false)
+ })
+
+ it('keeps the tunnel leg usable when cloudflared rewrites Host to a loopback authority', () => {
+ const rewritten = { 'host': '127.0.0.1:38999', 'origin': 'https://s2-probe.trycloudflare.com', 'sec-fetch-site': 'same-origin' }
+ expect(isCrossSiteRequest('tunnel', rewritten)).toBe(false)
+ expect(isCrossSiteRequest('inbound', rewritten)).toBe(true)
+ expect(isCrossSiteRequest('outbound', rewritten)).toBe(true)
+ expect(isCrossSiteRequest('tunnel', { 'host': 'localhost:38999', 'origin': 'https://s2-probe.trycloudflare.com', 'sec-fetch-site': 'same-origin' })).toBe(false)
+ expect(isCrossSiteRequest('tunnel', { 'host': '[::1]:38999', 'origin': 'https://s2-probe.trycloudflare.com', 'sec-fetch-site': 'same-origin' })).toBe(false)
+ expect(isCrossSiteRequest('inbound', { host: 'localhost:38999', origin: 'https://s2-probe.trycloudflare.com' })).toBe(true)
+ })
+
+ it('rejects same-site and headerless non-navigation requests once Host is rewritten', () => {
+ const base = { 'host': '127.0.0.1:38999', 'origin': 'https://evil.trycloudflare.com', 'sec-fetch-mode': 'cors' }
+ expect(isCrossSiteRequest('tunnel', { ...base, 'sec-fetch-site': 'same-site' })).toBe(true)
+ expect(isCrossSiteRequest('tunnel', base)).toBe(true)
+ expect(isCrossSiteRequest('tunnel', { ...base, 'sec-fetch-site': 'none' })).toBe(false)
+ expect(isCrossSiteRequest('tunnel', { ...base, 'sec-fetch-site': 'same-origin' })).toBe(false)
+ expect(isCrossSiteRequest('tunnel', { ...base, 'sec-fetch-site': 'cross-site' })).toBe(true)
+ expect(isCrossSiteRequest('tunnel', { 'host': '127.0.0.1:38999', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'navigate' })).toBe(false)
+ expect(isCrossSiteRequest('tunnel', { 'host': '127.0.0.1:38999', 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'navigate' })).toBe(false)
+ })
+
+ it('still compares Origin against Host on the tunnel leg while the tunnel domain survives', () => {
+ expect(isCrossSiteRequest('tunnel', { host: 's2-probe.trycloudflare.com', origin: 'https://s2-probe.trycloudflare.com' })).toBe(false)
+ expect(isCrossSiteRequest('tunnel', { host: 's2-probe.trycloudflare.com', origin: 'https://evil.example' })).toBe(true)
+ expect(isCrossSiteRequest('tunnel', { 'host': 's2-probe.trycloudflare.com', 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'no-cors' })).toBe(true)
+ expect(isCrossSiteRequest('tunnel', { 'host': 's2-probe.trycloudflare.com', 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'navigate' })).toBe(false)
+ })
+
+ it('accepts same-origin initiators on the tunnel leg by the tunnel public hostname', () => {
+ const rewritten = { 'host': '127.0.0.1:38999', 'origin': 'https://s2-probe.trycloudflare.com', 'sec-fetch-mode': 'cors' }
+ expect(isCrossSiteRequest('tunnel', rewritten, 's2-probe.trycloudflare.com')).toBe(false)
+ expect(isCrossSiteRequest('tunnel', { host: '127.0.0.1:38999', referer: 'https://s2-probe.trycloudflare.com/settings' }, 's2-probe.trycloudflare.com')).toBe(false)
+ expect(isCrossSiteRequest('tunnel', { ...rewritten, origin: 'https://evil.example' }, 's2-probe.trycloudflare.com')).toBe(true)
+ expect(isCrossSiteRequest('tunnel', rewritten, undefined)).toBe(true)
+ expect(isCrossSiteRequest('tunnel', { host: '127.0.0.1:38999', origin: 'https://s2-probe.trycloudflare.com:8443' }, 's2-probe.trycloudflare.com')).toBe(true)
+ expect(isCrossSiteRequest('tunnel', { ...rewritten, 'sec-fetch-site': 'cross-site' }, 's2-probe.trycloudflare.com')).toBe(true)
+ expect(isCrossSiteRequest('tunnel', { host: '127.0.0.1:38999', referer: 'https://evil.example/' }, 's2-probe.trycloudflare.com')).toBe(true)
+ expect(isCrossSiteRequest('inbound', { host: '127.0.0.1:3088', origin: 'https://s2-probe.trycloudflare.com' }, 's2-probe.trycloudflare.com')).toBe(false)
+ })
+})
+
+describe('negotiateEncoding', () => {
+ it('prefers zstd, then gzip, then identity', () => {
+ expect(negotiateEncoding('gzip, zstd', true)).toBe('zstd')
+ expect(negotiateEncoding('gzip, zstd', false)).toBe('gzip')
+ expect(negotiateEncoding('gzip', true)).toBe('gzip')
+ expect(negotiateEncoding('identity', true)).toBe('identity')
+ expect(negotiateEncoding(undefined, true)).toBe('identity')
+ expect(negotiateEncoding('', true)).toBe('identity')
+ })
+
+ it('falls back to identity when the client only accepts an unsupported coding', () => {
+ expect(negotiateEncoding('br', true)).toBe('identity')
+ expect(negotiateEncoding('br, deflate', true)).toBe('identity')
+ })
+
+ it('honours explicit quality values and the wildcard', () => {
+ expect(negotiateEncoding('zstd;q=0, gzip', true)).toBe('gzip')
+ expect(negotiateEncoding('*', true)).toBe('zstd')
+ expect(negotiateEncoding('*;q=0', true)).toBe('identity')
+ expect(negotiateEncoding('zstd;q=0.5, gzip;q=0.9', true)).toBe('zstd')
+ })
+})
+
+describe('acceptsEncoding', () => {
+ it('reports what the client declared', () => {
+ expect(acceptsEncoding('gzip', 'gzip')).toBe(true)
+ expect(acceptsEncoding('zstd, gzip', 'gzip')).toBe(true)
+ expect(acceptsEncoding('zstd', 'gzip')).toBe(false)
+ expect(acceptsEncoding('*', 'gzip')).toBe(true)
+ expect(acceptsEncoding('gzip;q=0', 'gzip')).toBe(false)
+ expect(acceptsEncoding(undefined, 'identity')).toBe(true)
+ expect(acceptsEncoding(undefined, 'gzip')).toBe(false)
+ })
+})
+
+describe('isCompressible / isEventStream', () => {
+ it.each(['text/html; charset=utf-8', 'application/json', 'text/plain', 'text/javascript', 'application/javascript', 'text/event-stream'])('compresses %s', (type) => {
+ expect(isCompressible(type)).toBe(true)
+ })
+
+ it.each(['image/png', 'image/svg+xml', 'audio/mpeg', 'video/mp4', 'font/woff2', 'application/zip', 'application/gzip', 'application/zstd', 'application/x-7z-compressed', 'application/x-tar'])('never compresses %s', (type) => {
+ expect(isCompressible(type)).toBe(false)
+ })
+
+ it('never compresses an undeclared content type', () => {
+ expect(isCompressible(undefined)).toBe(false)
+ expect(isCompressible('')).toBe(false)
+ })
+
+ it('detects the streaming content type only', () => {
+ expect(isEventStream('text/event-stream')).toBe(true)
+ expect(isEventStream('text/event-stream; charset=utf-8')).toBe(true)
+ expect(isEventStream('text/plain')).toBe(false)
+ expect(isEventStream(undefined)).toBe(false)
+ })
+})
+
+describe('responsePlanOf', () => {
+ const base = { acceptEncoding: 'zstd, gzip', contentType: 'application/json', contentLength: 4096, upstreamEncoding: undefined, supportsZstd: true, compress: true, minBytes: 1024 }
+
+ it('encodes a large compressible response with the negotiated coding', () => {
+ expect(responsePlanOf(base)).toEqual({ streaming: false, buffered: false, coding: 'zstd' })
+ })
+
+ it('keeps a response below the threshold as identity', () => {
+ expect(responsePlanOf({ ...base, contentLength: 1023 })).toEqual({ streaming: false, buffered: false })
+ expect(responsePlanOf({ ...base, contentLength: undefined })).toEqual({ streaming: false, buffered: true, coding: 'zstd' })
+ })
+
+ it('never compresses a non-compressible type regardless of size', () => {
+ expect(responsePlanOf({ ...base, contentType: 'image/png' })).toEqual({ streaming: false, buffered: false })
+ })
+
+ it('streams SSE without a size threshold', () => {
+ expect(responsePlanOf({ ...base, contentType: 'text/event-stream', contentLength: undefined })).toEqual({ streaming: true, buffered: false, coding: 'zstd' })
+ expect(responsePlanOf({ ...base, contentType: 'text/event-stream', contentLength: 10 })).toEqual({ streaming: true, buffered: false, coding: 'zstd' })
+ })
+
+ it('passes an upstream encoding through when the client accepts it', () => {
+ expect(responsePlanOf({ ...base, upstreamEncoding: 'gzip' })).toEqual({ streaming: false, buffered: false })
+ expect(responsePlanOf({ ...base, upstreamEncoding: 'gzip', acceptEncoding: 'zstd' })).toEqual({ streaming: false, buffered: false, decode: 'gzip', coding: 'zstd' })
+ })
+
+ it('decompresses without re-encoding when the client accepts no coding', () => {
+ expect(responsePlanOf({ ...base, upstreamEncoding: 'gzip', acceptEncoding: 'identity' })).toEqual({ streaming: false, buffered: false, decode: 'gzip' })
+ expect(responsePlanOf({ ...base, upstreamEncoding: 'gzip', contentType: 'image/png', acceptEncoding: 'zstd' })).toEqual({ streaming: false, buffered: false, decode: 'gzip' })
+ })
+
+ it('leaves the loopback leg on identity but still normalises an unacceptable upstream encoding', () => {
+ expect(responsePlanOf({ ...base, compress: false })).toEqual({ streaming: false, buffered: false })
+ expect(responsePlanOf({ ...base, compress: false, upstreamEncoding: 'gzip' })).toEqual({ streaming: false, buffered: false })
+ expect(responsePlanOf({ ...base, compress: false, upstreamEncoding: 'gzip', acceptEncoding: 'zstd' })).toEqual({ streaming: false, buffered: false, decode: 'gzip' })
+ })
+
+ it('re-encodes a decoded body regardless of the encoded length, so a small gzip still becomes zstd', () => {
+ expect(responsePlanOf({ ...base, upstreamEncoding: 'gzip', acceptEncoding: 'zstd', contentLength: 40 })).toEqual({ streaming: false, buffered: false, decode: 'gzip', coding: 'zstd' })
+ expect(responsePlanOf({ ...base, upstreamEncoding: 'br', acceptEncoding: 'gzip', contentLength: undefined })).toEqual({ streaming: false, buffered: false, decode: 'br', coding: 'gzip' })
+ })
+})
+
+describe('cookie helpers', () => {
+ it('extracts the pair from each set-cookie header', () => {
+ expect(cookiePairsOf(undefined)).toEqual([])
+ expect(cookiePairsOf(['dsh_a=1; Path=/; HttpOnly', 'dsh_b=2; Max-Age=10'])).toEqual(['dsh_a=1', 'dsh_b=2'])
+ expect(cookiePairsOf(['garbage'])).toEqual([])
+ })
+
+ it('parses a request cookie header into named pairs', () => {
+ const pairs = parseCookieHeader('a=1; b=2; malformed; c=')
+ expect(pairs.get('a')).toBe('1')
+ expect(pairs.get('b')).toBe('2')
+ expect(pairs.get('c')).toBe('')
+ expect(pairs.get('malformed')).toBeUndefined()
+ expect(parseCookieHeader(undefined).size).toBe(0)
+ })
+
+ it('keeps browser cookies and overrides same-named minted ones', () => {
+ expect(mergeCookieHeader('keep=1; dsh_session=stale', ['dsh_session=fresh'])).toBe('keep=1; dsh_session=fresh')
+ expect(mergeCookieHeader(undefined, ['dsh_session=fresh'])).toBe('dsh_session=fresh')
+ expect(mergeCookieHeader('keep=1', [])).toBe('keep=1')
+ expect(mergeCookieHeader(undefined, [])).toBeUndefined()
+ })
+
+ it('reads a urlencoded form field and ignores blanks', () => {
+ expect(parseFormField('password=s3cret&next=%2F', 'password')).toBe('s3cret')
+ expect(parseFormField('password=&next=%2F', 'password')).toBeUndefined()
+ expect(parseFormField('next=%2F', 'password')).toBeUndefined()
+ })
+})
+
+describe('tunnelClientIpOf', () => {
+ it('prefers the Cloudflare client address and falls back to the first forwarded hop', () => {
+ expect(tunnelClientIpOf({ 'cf-connecting-ip': '203.0.113.7', 'x-forwarded-for': '198.51.100.1' })).toBe('203.0.113.7')
+ expect(tunnelClientIpOf({ 'x-forwarded-for': '203.0.113.7, 10.0.0.1' })).toBe('203.0.113.7')
+ expect(tunnelClientIpOf({ 'x-forwarded-for': '2001:db8::7' })).toBe('2001:db8::7')
+ })
+
+ it('reports nothing for a missing or malformed declaration', () => {
+ expect(tunnelClientIpOf({})).toBeUndefined()
+ expect(tunnelClientIpOf({ 'cf-connecting-ip': 'not-an-ip' })).toBeUndefined()
+ expect(tunnelClientIpOf({ 'x-forwarded-for': 'unknown, 10.0.0.1' })).toBeUndefined()
+ })
+})
+
+describe('compressors', () => {
+ it('reports zstd support from the runtime API, never from a version guess', () => {
+ expect(supportsZstd()).toBe(typeof zlib.createZstdCompress === 'function')
+ })
+
+ it('round-trips a payload through zstd and gzip', async () => {
+ await expect(roundTrip('zstd', false, 'compressed payload')).resolves.toBe('compressed payload')
+ await expect(roundTrip('gzip', false, 'compressed payload')).resolves.toBe('compressed payload')
+ })
+
+ it('round-trips a streaming payload', async () => {
+ await expect(roundTrip('zstd', true, 'streamed payload')).resolves.toBe('streamed payload')
+ await expect(roundTrip('gzip', true, 'streamed payload')).resolves.toBe('streamed payload')
+ })
+
+ it('never builds a decompressor for an unknown coding', () => {
+ expect(createDecompressor('made-up')).toBeUndefined()
+ })
+})
+
+describe('loginPageHtml', () => {
+ it('posts the password back to the current URL without inventing another route', () => {
+ const html = loginPageHtml()
+ expect(html).toContain('<form method="post">')
+ expect(html).toContain('name="password"')
+ expect(html).not.toContain('action=')
+ })
+
+ it('renders the official branding and accessible pairing form without client assets', () => {
+ const html = loginPageHtml()
+ expect(html).toContain('<h1>DeepSeek Harness</h1>')
+ expect(html).toContain('<svg')
+ expect(html).toContain('viewBox="0 0 23.16 17.04"')
+ expect(html).toContain('<label for="password">请输入配对码</label>')
+ expect(html).toMatch(/<input[^>]*id="password"[^>]*name="password"/)
+ expect(html).toMatch(/<button[^>]*type="submit"[^>]*>连接<\/button>/)
+ expect(html).not.toMatch(/<script|<link|\bsrc=|maxlength=|__ModuleLoader__/i)
+ })
+
+ it('inlines the official control styles and theme tokens with matching classes', () => {
+ const html = loginPageHtml()
+ const style = html.match(/<style>([\s\S]*?)<\/style>/)?.[1] ?? ''
+ expect(style).toContain('--ds-')
+ expect(style).toMatch(/prefers-color-scheme:\s*dark/)
+ expect(style).not.toMatch(/@import|url\(/)
+ const classes = [...html.matchAll(/class="([^"]+)"/g)].flatMap(match => match[1]!.split(' '))
+ expect(classes.length).toBeGreaterThanOrEqual(4)
+ for (const className of classes)
+ expect(style).toContain(`.${className}`)
+ })
+
+ it('renders and escapes the failure message', () => {
+ const html = loginPageHtml('<script>x</script>&"')
+ expect(html).toContain('&lt;script&gt;x&lt;/script&gt;&amp;&quot;')
+ expect(html).toContain('role="alert"')
+ expect(html).not.toContain('<script>x</script>')
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/host/service/gateway.utils.ts b/packages/dsh-tauri-remote/src/host/service/gateway.utils.ts
new file mode 100644
index 00000000..1e2336e8
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/gateway.utils.ts
@@ -0,0 +1,362 @@
+import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'node:http'
+import type { Transform } from 'node:stream'
+import type { RemoteGatewayEntryKind } from '../types/index'
+import type { RemoteForwardPlan, RemoteResponsePlan, RemoteResponsePlanInput } from './gateway.types'
+import * as zlib from 'node:zlib'
+import { GATEWAY_SESSION_HEADER, GATEWAY_SOURCE_HEADER } from '../config/constants'
+import { classifyPeer, isIpAddress } from '../utils/source'
+
+declare const __GATEWAY_AUTH_HTML__: string
+
+const AUTH_HTML = typeof __GATEWAY_AUTH_HTML__ === 'string'
+ ? __GATEWAY_AUTH_HTML__
+ // eslint-disable-next-line antfu/no-top-level-await -- 源码测试复用构建期模板;宿主产物通过 define 删除该分支。
+ : await import('./gateway.auth').then(module => module.gatewayAuthHtml())
+
+const HOP_BY_HOP = new Set([
+ 'connection',
+ 'keep-alive',
+ 'proxy-authenticate',
+ 'proxy-authorization',
+ 'te',
+ 'trailer',
+ 'transfer-encoding',
+ 'upgrade',
+])
+
+const BINARY_TYPE = /^(?:image|audio|video|font)\//
+
+const ARCHIVE_TYPE = /^application\/(?:zip|gzip|x-gzip|x-7z-compressed|x-rar-compressed|vnd\.rar|x-tar|zstd|x-bzip2|x-bzip|x-lzma|x-xz|x-compress)$/
+
+const IDENTITY = 'identity'
+
+/** 转发时使用的上游 authority(S2 §5.1):出站取浏览器所见的网关回环端口,入站取上游自身的回环 authority。 */
+export function authorityFor(kind: RemoteGatewayEntryKind, upstream: URL, port: number): string {
+ return kind === 'outbound' ? `127.0.0.1:${port}` : upstream.host
+}
+
+export function entryUrlOf(host: string, port: number): string {
+ return `http://${host.includes(':') ? `[${host}]` : host}:${port}`
+}
+
+export function upstreamPortOf(upstream: URL): number {
+ return upstream.port === '' ? 80 : Number(upstream.port)
+}
+
+/**
+ * 请求头改写与注入:Host 一律改写为转发 authority;Origin 存在时对齐到同一 authority;两枚内部
+ * 来源标识头先剥离再按计划写入;非升级请求丢弃
+ * 逐跳头;出站腿对上游声明 identity,避免与 SSH 链路压缩叠加。
+ *
+ * 非升级请求还必须自带分帧:transfer-encoding 属于逐跳头会被剥掉,而 Node 的客户端只为 POST/PUT/PATCH
+ * 默认启用分块,其余方法(GET/HEAD/DELETE/OPTIONS/TRACE/CONNECT)会把已解码的正文当**裸尾部字节**写出,
+ * 客户端可控的那串字节于是能在上游连接上拼出第二个请求。这里按上游声明的分帧重建:有可信长度就带
+ * content-length,否则显式声明 chunked 让 Node 重新分块,任何形态都自描述。
+ */
+export function forwardHeadersOf(headers: IncomingHttpHeaders, plan: RemoteForwardPlan): OutgoingHttpHeaders {
+ const out: OutgoingHttpHeaders = {}
+ const passthroughHopByHop = plan.upgrade === true
+ for (const [name, value] of Object.entries(headers)) {
+ if (value === undefined)
+ continue
+ const lower = name.toLowerCase()
+ if (lower === GATEWAY_SOURCE_HEADER || lower === GATEWAY_SESSION_HEADER || lower === 'host' || lower === 'origin')
+ continue
+ if (!passthroughHopByHop && HOP_BY_HOP.has(lower))
+ continue
+ out[lower] = value
+ }
+ if (!passthroughHopByHop)
+ reframeBody(headers, out)
+ out.host = plan.authority
+ const origin = headers.origin
+ if (typeof origin === 'string' && origin !== '')
+ out.origin = `http://${plan.authority}`
+ if (plan.source !== undefined && plan.session !== undefined && plan.session !== '') {
+ out[GATEWAY_SOURCE_HEADER] = plan.source
+ out[GATEWAY_SESSION_HEADER] = plan.session
+ }
+ if (plan.identity === true)
+ out['accept-encoding'] = IDENTITY
+ return out
+}
+
+export function responseHeadersOf(headers: IncomingHttpHeaders): OutgoingHttpHeaders {
+ const out: OutgoingHttpHeaders = {}
+ for (const [name, value] of Object.entries(headers)) {
+ if (value === undefined || HOP_BY_HOP.has(name.toLowerCase()))
+ continue
+ out[name.toLowerCase()] = value
+ }
+ return out
+}
+
+function headerText(value: number | string | string[] | undefined): string | undefined {
+ if (Array.isArray(value))
+ return value[0]
+ return value === undefined ? undefined : String(value)
+}
+
+export function isUpgradeOf(headers: IncomingHttpHeaders): boolean {
+ if (typeof headers.upgrade === 'string' && headers.upgrade !== '')
+ return true
+ const connection = headers.connection
+ return typeof connection === 'string' && connection.toLowerCase().split(',').some(token => token.trim() === 'upgrade')
+}
+
+export function isNavigationRequest(headers: IncomingHttpHeaders): boolean {
+ const accept = headers.accept
+ return typeof accept === 'string' && accept.toLowerCase().includes('text/html')
+}
+
+/**
+ * 跨站发起方判定:网关会把任何非空 Origin 改写成回环 authority,因此必须在改写前拦下跨站来源,
+ * 否则上游仅存的 `sec-fetch-site` 防线(WebSocket 握手不带该头时只剩 Origin)会被抹平。
+ * 同源判定以浏览器实际使用的 Host 为准;隧道腿的 Host 由 cloudflared 改写成回环 authority,
+ * 该比对无从进行,此时以隧道**公网主机名**为准:Origin / Referer 命中该主机名即同源,跨站页面
+ * 的 Origin 必然不同,仍被拦下。Safari 与旧浏览器不发 Fetch 元数据(`sec-fetch-site`),
+ * 只靠该头会让本机浏览器也进不来,因此主机名命中优先于元数据判定。
+ * 元数据仍用于补强:非导航请求在隧道腿上只接受 `same-origin` / `none`
+ * (`same-site` 说明是同一注册域下的兄弟子域,SameSite=Lax 会话 cookie 会被带上,必须拒绝),
+ * 元数据缺失且又无 Origin / Referer 可对时一律拒绝。
+ * 跨站的文档导航(壳层 iframe、外站链接)一律放行:落地文档的源随即变成入口自身,后续请求都同源。
+ */
+export function isCrossSiteRequest(kind: RemoteGatewayEntryKind, headers: IncomingHttpHeaders, publicHost?: string | undefined): boolean {
+ const rewritten = hostRewritten(kind, headers)
+ const origin = headerText(headers.origin)
+ if (origin !== undefined && origin !== '') {
+ if (isSamePublicHost(origin, publicHost) && headerText(headers['sec-fetch-site']) !== 'cross-site')
+ return false
+ if (!rewritten) {
+ const host = headerText(headers.host)
+ if (host === undefined || host === '')
+ return true
+ try {
+ if (new URL(origin).host !== new URL(`http://${host}`).host)
+ return true
+ }
+ catch {
+ return true
+ }
+ }
+ }
+ else if (isSamePublicHost(headerText(headers.referer), publicHost)) {
+ return false
+ }
+ const site = headerText(headers['sec-fetch-site'])
+ const navigate = headerText(headers['sec-fetch-mode']) === 'navigate'
+ if (site !== 'cross-site')
+ return rewritten && !navigate && site !== 'same-origin' && site !== 'none'
+ return !navigate
+}
+
+/** 可重放 = 无请求体:请求体一旦开始发送就不重试(S2 §6 失效列)。 */
+export function isReplayable(headers: IncomingHttpHeaders): boolean {
+ if (headers['transfer-encoding'] !== undefined)
+ return false
+ const length = headers['content-length']
+ return length === undefined || length === '0'
+}
+
+export function negotiateEncoding(acceptEncoding: string | undefined, supportsZstd: boolean): 'zstd' | 'gzip' | 'identity' {
+ const quality = parseQuality(acceptEncoding)
+ if (quality.size === 0)
+ return IDENTITY
+ if (supportsZstd && qualityOf(quality, 'zstd') > 0)
+ return 'zstd'
+ return qualityOf(quality, 'gzip') > 0 ? 'gzip' : IDENTITY
+}
+
+export function acceptsEncoding(acceptEncoding: string | undefined, coding: string): boolean {
+ const quality = parseQuality(acceptEncoding)
+ if (quality.size === 0)
+ return coding === IDENTITY
+ return qualityOf(quality, coding) > 0
+}
+
+export function isCompressible(contentType: string | undefined): boolean {
+ if (contentType === undefined || contentType === '')
+ return false
+ const type = (contentType.split(';')[0] ?? '').trim().toLowerCase()
+ if (type === '' || BINARY_TYPE.test(type))
+ return false
+ return !ARCHIVE_TYPE.test(type)
+}
+
+export function isEventStream(contentType: string | undefined): boolean {
+ return contentType !== undefined && /^text\/event-stream\b/i.test(contentType.trim())
+}
+
+/** 响应体处理计划(S2 §8.2/§8.3):上游编码可接受即原样透传;否则解压后按下游协商重压。 */
+export function responsePlanOf(input: RemoteResponsePlanInput): RemoteResponsePlan {
+ const streaming = isEventStream(input.contentType)
+ const upstream = input.upstreamEncoding?.trim().toLowerCase()
+ const encoded = upstream !== undefined && upstream !== '' && upstream !== IDENTITY
+ const passthroughUpstream = encoded && acceptsEncoding(input.acceptEncoding, upstream)
+ const plan: RemoteResponsePlan = { streaming, buffered: false }
+ if (passthroughUpstream)
+ return plan
+ const decoded: RemoteResponsePlan = encoded ? { ...plan, decode: upstream } : plan
+ if (!input.compress)
+ return decoded
+ const coding = isCompressible(input.contentType) ? negotiateEncoding(input.acceptEncoding, input.supportsZstd) : IDENTITY
+ if (coding === IDENTITY)
+ return decoded
+ if (streaming || decoded.decode !== undefined)
+ return { ...decoded, coding }
+ if (input.contentLength !== undefined)
+ return input.contentLength >= input.minBytes ? { ...decoded, coding } : decoded
+ return { ...decoded, coding, buffered: true }
+}
+
+export function supportsZstd(): boolean {
+ return typeof zlib.createZstdCompress === 'function'
+}
+
+/** SSE 逐块 flush:`flush: Z_SYNC_FLUSH` 使每次写入立即产出压缩块,不做任何聚合。 */
+export function createCompressor(coding: 'zstd' | 'gzip', streaming: boolean): Transform {
+ const options = streaming ? { flush: zlib.constants.Z_SYNC_FLUSH } : {}
+ return coding === 'zstd' ? zlib.createZstdCompress(options) : zlib.createGzip(options)
+}
+
+export function createDecompressor(encoding: string): Transform | undefined {
+ switch (encoding) {
+ case 'gzip':
+ case 'x-gzip':
+ return zlib.createGunzip()
+ case 'deflate':
+ return zlib.createInflate()
+ case 'br':
+ return zlib.createBrotliDecompress()
+ case 'zstd':
+ return typeof zlib.createZstdDecompress === 'function' ? zlib.createZstdDecompress() : undefined
+ default:
+ return undefined
+ }
+}
+
+export function cookiePairsOf(setCookie: string[] | undefined): string[] {
+ if (setCookie === undefined)
+ return []
+ return setCookie.map(pair => (pair.split(';')[0] ?? '').trim()).filter(pair => /^[^=;]+=[^;]*$/.test(pair))
+}
+
+export function mergeCookieHeader(existing: string | undefined, minted: string[]): string | undefined {
+ const names = new Set(minted.map(pair => pair.slice(0, pair.indexOf('='))))
+ const kept = (existing ?? '')
+ .split(';')
+ .map(pair => pair.trim())
+ .filter(pair => pair !== '' && !names.has(pair.slice(0, pair.indexOf('='))))
+ const merged = [...kept, ...minted]
+ return merged.length === 0 ? undefined : merged.join('; ')
+}
+
+export function parseCookieHeader(value: string | undefined): Map<string, string> {
+ const pairs = new Map<string, string>()
+ for (const segment of (value ?? '').split(';')) {
+ const at = segment.indexOf('=')
+ if (at === -1)
+ continue
+ const name = segment.slice(0, at).trim()
+ if (name !== '')
+ pairs.set(name, segment.slice(at + 1).trim())
+ }
+ return pairs
+}
+
+export function parseFormField(body: string, name: string): string | undefined {
+ const value = new URLSearchParams(body).get(name)
+ return value === null || value === '' ? undefined : value
+}
+
+/** 隧道侧声明的客户端 IP:只用于限速分桶,绝不参与放行判定(S2 §7.1)。 */
+export function tunnelClientIpOf(headers: IncomingHttpHeaders): string | undefined {
+ const direct = headers['cf-connecting-ip']
+ const declared = typeof direct === 'string' ? direct.trim() : undefined
+ if (isIpAddress(declared))
+ return declared
+ const forwarded = headers['x-forwarded-for']
+ const first = (typeof forwarded === 'string' ? forwarded : '').split(',')[0]?.trim()
+ return isIpAddress(first) ? first : undefined
+}
+
+export function loginPageHtml(message?: string): string {
+ return AUTH_HTML.replace('__GATEWAY_AUTH_MESSAGE__', () => message === undefined ? '' : `<p role="alert">${escapeHtml(message)}</p>`)
+}
+
+export function deniedHtml(reason: string): string {
+ return [
+ '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">',
+ '<meta name="viewport" content="width=device-width,initial-scale=1">',
+ '<title>访问被拒绝</title></head><body>',
+ `<main><h1>访问被拒绝</h1><p>${escapeHtml(reason)}</p></main>`,
+ '</body></html>',
+ ].join('')
+}
+
+// --- internal ---
+function isSamePublicHost(value: string | undefined, publicHost: string | undefined): boolean {
+ if (value === undefined || value === '' || publicHost === undefined || publicHost === '')
+ return false
+ try {
+ return new URL(value).host === publicHost
+ }
+ catch {
+ return false
+ }
+}
+
+function hostRewritten(kind: RemoteGatewayEntryKind, headers: IncomingHttpHeaders): boolean {
+ if (kind !== 'tunnel')
+ return false
+ const host = headerText(headers.host)
+ if (host === undefined || host === '')
+ return false
+ try {
+ const hostname = new URL(`http://${host}`).hostname
+ const bare = hostname.startsWith('[') ? hostname.slice(1, -1) : hostname
+ return bare === 'localhost' || bare.endsWith('.localhost') || classifyPeer(bare) === 'loopback'
+ }
+ catch {
+ return false
+ }
+}
+
+function reframeBody(incoming: IncomingHttpHeaders, out: OutgoingHttpHeaders): void {
+ if (incoming['transfer-encoding'] !== undefined && incoming['transfer-encoding'] !== '') {
+ out['transfer-encoding'] = 'chunked'
+ return
+ }
+ const declared = headerText(incoming['content-length'])
+ if (declared === undefined)
+ return
+ const length = Number(declared)
+ if (Number.isInteger(length) && length >= 0)
+ out['content-length'] = length
+ else
+ out['transfer-encoding'] = 'chunked'
+}
+
+function parseQuality(acceptEncoding: string | undefined): Map<string, number> {
+ const quality = new Map<string, number>()
+ if (acceptEncoding === undefined)
+ return quality
+ for (const entry of acceptEncoding.split(',')) {
+ const [rawToken, ...parameters] = entry.split(';')
+ const token = (rawToken ?? '').trim().toLowerCase()
+ if (token === '')
+ continue
+ const rawQuality = parameters.map(parameter => parameter.trim()).find(parameter => parameter.startsWith('q='))
+ const parsed = rawQuality === undefined ? 1 : Number(rawQuality.slice(2))
+ quality.set(token, Number.isFinite(parsed) ? parsed : 0)
+ }
+ return quality
+}
+
+function qualityOf(quality: Map<string, number>, coding: string): number {
+ return quality.get(coding) ?? quality.get('*') ?? 0
+}
+
+function escapeHtml(value: string): string {
+ return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;')
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/known-hosts.test.ts b/packages/dsh-tauri-remote/src/host/service/known-hosts.test.ts
similarity index 98%
rename from packages/dsh-tauri-ssh/src/host/service/known-hosts.test.ts
rename to packages/dsh-tauri-remote/src/host/service/known-hosts.test.ts
index 87db9c20..37f82098 100644
--- a/packages/dsh-tauri-ssh/src/host/service/known-hosts.test.ts
+++ b/packages/dsh-tauri-remote/src/host/service/known-hosts.test.ts
@@ -4,13 +4,13 @@ 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 { resetRuntime, setKnownHostsPath } from '../config/runtime'
+import { clearHostRuntime, setKnownHostsPath } from '../config/runtime'
import { MachineId } from '../types/index'
import { knownHosts } from './known-hosts'
import { fingerprintHostKey } from './known-hosts.utils'
function open(file: string): typeof knownHosts {
- resetRuntime()
+ clearHostRuntime()
setKnownHostsPath(file)
return knownHosts
}
diff --git a/packages/dsh-tauri-ssh/src/host/service/known-hosts.ts b/packages/dsh-tauri-remote/src/host/service/known-hosts.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/known-hosts.ts
rename to packages/dsh-tauri-remote/src/host/service/known-hosts.ts
diff --git a/packages/dsh-tauri-ssh/src/host/service/known-hosts.types.ts b/packages/dsh-tauri-remote/src/host/service/known-hosts.types.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/known-hosts.types.ts
rename to packages/dsh-tauri-remote/src/host/service/known-hosts.types.ts
diff --git a/packages/dsh-tauri-ssh/src/host/service/known-hosts.utils.ts b/packages/dsh-tauri-remote/src/host/service/known-hosts.utils.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/known-hosts.utils.ts
rename to packages/dsh-tauri-remote/src/host/service/known-hosts.utils.ts
diff --git a/packages/dsh-tauri-ssh/src/host/service/machine.test.ts b/packages/dsh-tauri-remote/src/host/service/machine.test.ts
similarity index 75%
rename from packages/dsh-tauri-ssh/src/host/service/machine.test.ts
rename to packages/dsh-tauri-remote/src/host/service/machine.test.ts
index e93c4881..784d9e55 100644
--- a/packages/dsh-tauri-ssh/src/host/service/machine.test.ts
+++ b/packages/dsh-tauri-remote/src/host/service/machine.test.ts
@@ -1,17 +1,19 @@
-import type { AddressInfo } from 'node:net'
-import type { MachineProfile, SshExecOptions, SshExecResult, SshMachineEvent, SshSession, SshTunnelHandle } from '../types/index'
-import type { SshTransport, SshTransportOptions } from './transport.types'
+import type { AddressInfo, Server } from 'node:net'
+import type { MachineProfile, RemoteExecOptions, RemoteExecResult, RemoteMachineEvent, RemoteSession, RemoteStreamHandle } from '../types/index'
+import type { RemoteTransport, RemoteTransportCapabilities, RemoteTransportOptions } from './transport.types'
import { Buffer } from 'node:buffer'
import { execFileSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
-import { createServer } from 'node:http'
+import { createServer, get, request } from 'node:http'
+import { Server as NetServer } from 'node:net'
import { tmpdir } from 'node:os'
import { join } from 'pathe'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { machineStates, machineTable, resetRuntime, setHostConfig, setKnownHostsPath, setMachineDeps } from '../config/runtime'
-import { MachineId, SshError } from '../types/index'
+import { clearHostRuntime, machineStates, machineTable, setHostConfig, setKnownHostsPath, setMachineDeps } from '../config/runtime'
+import { MachineId, RemoteError } from '../types/index'
import { EMPTY_ALLOWLIST } from '../utils/allowlist'
import { events } from './events'
+import { gateway } from './gateway'
import { machine } from './machine'
const profile: MachineProfile = {
@@ -65,11 +67,11 @@ const BOOT_HTML = '<html><body><script>globalThis["__DSH_BOOT__"] = {"entries":[
/** The layout entry the pinned dsh release resolves: the remote shell expands $HOME (root user in the fake). */
const ENTRY = '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js'
-class FakeSession implements SshSession {
+class FakeSession implements RemoteSession {
commands: string[] = []
- options: SshExecOptions[] = []
+ options: RemoteExecOptions[] = []
closed = false
- tunnel: SshTunnelHandle | undefined
+ tunnel: RemoteStreamHandle | undefined
closeCalls = 0
tunnelCloseCalls = 0
closeError: Error | undefined
@@ -77,9 +79,9 @@ class FakeSession implements SshSession {
tunnelGate: Promise<void> | undefined
tunnelStarted: (() => void) | undefined
execGate: ((command: string, index: number) => Promise<void> | undefined) | undefined
- /** The preferred local port the last openTunnel call received. */
+ /** The preferred local port the last stream call received. */
preferredTunnelPort: number | undefined
- authMethod: SshSession['authMethod'] = 'key'
+ authMethod: RemoteSession['authMethod'] = 'key'
private closedCallbacks: Array<() => void> = []
constructor(
@@ -102,10 +104,10 @@ class FakeSession implements SshSession {
/** The web-log token grep answer (default: no token → bare tunnel URL). */
webTokenResult = ''
- exec(command: string, options?: SshExecOptions): Promise<SshExecResult> {
+ exec(command: string, options?: RemoteExecOptions): Promise<RemoteExecResult> {
this.commands.push(command)
this.options.push(options ?? {})
- const respond = (): SshExecResult => {
+ const respond = (): RemoteExecResult => {
if (this.connectError !== undefined)
throw this.connectError
if (command === 'uname -srm') {
@@ -178,11 +180,7 @@ class FakeSession implements SshSession {
/** The stdout the credentials-copy command answers (default: copied). */
credentialsAnswer = 'copied'
- /** The injection slot the last openTunnel call received. */
- tunnelInjection: { cookie: string | undefined } | undefined
-
- async openTunnel(_remotePort: number, preferredLocalPort?: number, injection?: { cookie: string | undefined }): Promise<SshTunnelHandle> {
- this.tunnelInjection = injection
+ async stream(_remotePort: number, preferredLocalPort?: number): Promise<RemoteStreamHandle> {
this.preferredTunnelPort = preferredLocalPort
this.tunnelStarted?.()
if (this.tunnelGate !== undefined)
@@ -215,22 +213,23 @@ class FakeSession implements SshSession {
}
}
-class FakeTransport implements SshTransport {
+class FakeTransport implements RemoteTransport {
sessions: FakeSession[] = []
connectCalls = 0
hostKeys: Array<{ key: Buffer, accepted: boolean }> = []
rejectKeys = false
/** The profile each connect call received (the loop must re-read edits). */
profiles: MachineProfile[] = []
+ capabilities: RemoteTransportCapabilities = { exec: true, stream: true }
constructor(private readonly sessionFactory: () => FakeSession) {}
async connect(
profile: MachineProfile,
hostKeyVerifier: (label: string, key: Buffer) => boolean | Promise<boolean>,
- _options: SshTransportOptions,
+ _options: RemoteTransportOptions,
_signal?: AbortSignal,
- ): Promise<SshSession> {
+ ): Promise<RemoteSession> {
this.connectCalls += 1
this.profiles.push(profile)
const session = this.sessionFactory()
@@ -292,6 +291,7 @@ afterEach(async () => {
finally {
try {
await machine.dispose()
+ await gateway.dispose()
await settleRuntime()
}
finally {
@@ -302,7 +302,7 @@ afterEach(async () => {
process.env.DSH_HOME = harnessHomeBefore
vi.unstubAllGlobals()
vi.restoreAllMocks()
- resetRuntime()
+ clearHostRuntime()
}
}
})
@@ -338,21 +338,23 @@ function boot(overrides: Partial<{
envCredentials: () => { apiKey?: string, baseUrl?: string }
config: typeof config
localAllowlist: () => import('../utils/allowlist').WorkspaceAllowlist
+ capabilities: Partial<RemoteTransportCapabilities>
}> = {}) {
const transport = new FakeTransport(overrides.sessionFactory ?? (() => new FakeSession(() => true)))
transport.rejectKeys = overrides.rejectKeys ?? false
+ transport.capabilities = { ...transport.capabilities, ...overrides.capabilities }
const emits: Array<{ id: MachineId, state: string, progress?: { phase: string } }> = []
- resetRuntime()
+ clearHostRuntime()
if (overrides.envCredentials !== undefined)
process.env.DSH_HOME = harnessHomeWith(overrides.envCredentials())
setHostConfig({ ...(overrides.config ?? config), sshDir: tempRoot() })
setKnownHostsPath(join(tempRoot(), 'known-hosts.json'))
const bundledPluginsRoot = tempRoot()
- mkdirSync(join(bundledPluginsRoot, 'dsh-tauri-ssh'))
- writeFileSync(join(bundledPluginsRoot, 'dsh-tauri-ssh', 'package.json'), JSON.stringify({ name: 'dsh-tauri-ssh', dsh: { bundle: {} } }))
+ mkdirSync(join(bundledPluginsRoot, 'dsh-tauri-remote'))
+ writeFileSync(join(bundledPluginsRoot, 'dsh-tauri-remote', 'package.json'), JSON.stringify({ name: 'dsh-tauri-remote', dsh: { bundle: {} } }))
setMachineDeps({
- transport,
- bundledPluginsTree: { root: bundledPluginsRoot, pluginNames: ['dsh-tauri-ssh'] },
+ transport: { resolve: () => transport },
+ bundledPluginsTree: { root: bundledPluginsRoot, pluginNames: ['dsh-tauri-remote'] },
localAllowlist: overrides.localAllowlist ?? (() => EMPTY_ALLOWLIST),
emitStatus: (id, status) => {
emits.push({ id, state: status.state, ...status.progress === undefined ? {} : { progress: status.progress } })
@@ -365,10 +367,158 @@ function boot(overrides: Partial<{
}
/** The terminal (settling) events one machine's channel recorded. */
-function terminalsOf(log: typeof events): SshMachineEvent[] {
+function terminalsOf(log: typeof events): RemoteMachineEvent[] {
return log.since(MachineId('m1')).events.filter(event => event.terminal !== undefined)
}
+/** 网关候选端口数:首选端口 + 20 次回落(S2 的端口回落语义,测试侧独立固定)。 */
+const GATEWAY_CANDIDATES = 21
+
+interface StandInRecord {
+ url: string
+ host: string | undefined
+ encoding: string | undefined
+ cookie: string | undefined
+}
+
+interface RemoteStandIn {
+ port: number
+ records: StandInRecord[]
+ /** 远端实例当前认可的会话 cookie;重启后换新值,旧 cookie 随即 401。 */
+ sessionCookie: (value: string) => void
+ close: () => Promise<void>
+}
+
+/**
+ * 远端 DSH 的替身:`/?token=<t>` 铸造 `dsh-session=<t>`,其余请求只在带上当前有效
+ * cookie 时回 200,否则 401。每条请求的 Host / Accept-Encoding / Cookie 都被记录,
+ * 供出站腿的改写与注入断言使用。
+ */
+async function remoteStandIn(port = 0): Promise<RemoteStandIn> {
+ const records: StandInRecord[] = []
+ let accepted = 'dsh-session=tok-abc-123'
+ const server = createServer((request, response) => {
+ const url = request.url ?? ''
+ records.push({
+ url,
+ host: request.headers.host,
+ encoding: request.headers['accept-encoding'],
+ cookie: request.headers.cookie,
+ })
+ const token = new URLSearchParams(url.slice(url.indexOf('?'))).get('token')
+ if (url.startsWith('/?token=') && token !== null) {
+ response.setHeader('set-cookie', [`dsh-session=${token}; Path=/; HttpOnly`])
+ response.end('minted')
+ return
+ }
+ if (request.headers.cookie !== accepted) {
+ response.statusCode = 401
+ response.end('unauthorized')
+ return
+ }
+ response.end('dsh-ok')
+ })
+ await new Promise<void>((resolve) => {
+ server.listen(port, '127.0.0.1', () => resolve())
+ })
+ return {
+ port: (server.address() as AddressInfo).port,
+ records,
+ sessionCookie: (value: string) => {
+ accepted = value
+ },
+ close: async () => {
+ await new Promise<void>((resolve) => {
+ server.close(() => resolve())
+ })
+ },
+ }
+}
+
+/** stand-in 的会话替身:隧道口指向 stand-in,启动 token 取用远端日志里的那一枚。 */
+function standInSession(standIn: RemoteStandIn): FakeSession {
+ const session = new FakeSession(() => true)
+ session.webTokenResult = 'tok-abc-123\n'
+ session.tunnelPort = standIn.port
+ return session
+}
+
+function getThrough(url: string): Promise<{ status: number, body: string }> {
+ return new Promise((resolve, reject) => {
+ const request = get(url, (response) => {
+ let body = ''
+ response.on('data', (chunk: Buffer) => {
+ body += chunk.toString('utf8')
+ })
+ response.on('end', () => resolve({ status: response.statusCode ?? 0, body }))
+ })
+ request.on('error', reject)
+ })
+}
+
+function listenAt(port: number): Promise<Server> {
+ const server = new NetServer()
+ return new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(port, '127.0.0.1', () => resolve(server))
+ })
+}
+
+/**
+ * 隧道口与远端实例之间的第二跳:`instanceAlive()` 取假时照真实观感把该条连接掐断(没有状态行),
+ * 于是隧道口仍在而实例已死——这正是「逐请求失败」与「链路丢失」的区别所在。隧道口本身的死活
+ * 由调用方直接关掉本服务器表达。
+ */
+function hopThrough(target: number, instanceAlive: () => boolean): Promise<{ port: number, close: () => Promise<void> }> {
+ const server = createServer((incoming, outgoing) => {
+ if (!instanceAlive()) {
+ outgoing.destroy()
+ incoming.resume()
+ return
+ }
+ const forwarded = request({ host: '127.0.0.1', port: target, method: incoming.method, path: incoming.url, headers: { ...incoming.headers, connection: 'close' } }, (response) => {
+ outgoing.writeHead(response.statusCode ?? 502, response.headers)
+ response.pipe(outgoing)
+ })
+ forwarded.on('error', () => outgoing.destroy())
+ incoming.pipe(forwarded)
+ })
+ return new Promise((resolve) => {
+ server.listen(0, '127.0.0.1', () => resolve({
+ port: (server.address() as AddressInfo).port,
+ close: async () => {
+ await new Promise<void>((done) => {
+ server.close(() => done())
+ })
+ },
+ }))
+ })
+}
+
+async function closeServers(servers: Server[]): Promise<void> {
+ for (const server of servers)
+ await new Promise<void>((resolve) => { server.close(() => resolve()) })
+}
+
+/** 连续 count 个空闲回环端口的占用者:`preferred` 起优先,不成则扫描一段静态范围,绝不静默降级为更弱的用例。 */
+async function occupyRange(count: number, preferred: number): Promise<{ base: number, servers: Server[] }> {
+ const bases = [preferred]
+ for (let base = 20_000; base < 60_000; base += count + 1)
+ bases.push(base)
+ for (const base of bases) {
+ const servers: Server[] = []
+ try {
+ for (let offset = 0; offset < count; offset += 1)
+ servers.push(await listenAt(base + offset))
+ return { base, servers }
+ }
+ catch {
+ await closeServers(servers)
+ }
+ }
+ throw new Error(`找不到连续 ${count} 个空闲回环端口`)
+}
+
describe('sshManager', () => {
it('lists redacted profile views in settings order', () => {
const { manager } = boot()
@@ -393,11 +543,13 @@ describe('sshManager', () => {
expect(manager.link(MachineId('ghost'))).toBeUndefined()
})
- it('connects a healthy machine and publishes the link', async () => {
+ it('connects a healthy machine and publishes the gateway 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(link.tunnelBaseUrl).toBe(manager.status(MachineId('m1')).tunnelBaseUrl)
+ expect(link.tunnelBaseUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/u)
+ expect(link.tunnelBaseUrl).not.toContain('token')
+ expect(manager.link(MachineId('m1'))).toEqual(link)
expect(manager.status(MachineId('m1')).state).toBe('connected')
expect(transport.connectCalls).toBe(1)
expect(transport.hostKeys[0]?.accepted).toBe(true)
@@ -473,12 +625,12 @@ describe('sshManager', () => {
it('publishes and clears externally driven progress (the sync engine)', () => {
const { manager, emits } = boot()
- manager.setProgress(MachineId('m1'), { phase: 'syncing', attempt: 3, total: 13, item: 'dsh-tauri-ssh' })
- expect(manager.status(MachineId('m1')).progress).toEqual({ phase: 'syncing', attempt: 3, total: 13, item: 'dsh-tauri-ssh' })
+ manager.setProgress(MachineId('m1'), { phase: 'syncing', attempt: 3, total: 13, item: 'dsh-tauri-remote' })
+ expect(manager.status(MachineId('m1')).progress).toEqual({ phase: 'syncing', attempt: 3, total: 13, item: 'dsh-tauri-remote' })
manager.setProgress(MachineId('m1'))
expect(manager.status(MachineId('m1')).progress).toBeUndefined()
expect(emits.map(entry => entry.progress)).toEqual([
- { phase: 'syncing', attempt: 3, total: 13, item: 'dsh-tauri-ssh' },
+ { phase: 'syncing', attempt: 3, total: 13, item: 'dsh-tauri-remote' },
undefined,
])
})
@@ -539,7 +691,7 @@ describe('sshManager', () => {
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.toThrow(RemoteError)
await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-reconnecting' })
await untilSettled(manager)
const status = manager.status(MachineId('m1'))
@@ -677,6 +829,35 @@ describe('sshManager', () => {
expect(manager.status(MachineId('m1')).state).toBe('disconnected')
})
+ it('cancels an in-flight connect that disconnects while the gateway entry is starting', async () => {
+ let releaseStart: (() => void) | undefined
+ let markStartEntered: (() => void) | undefined
+ const gate = new Promise<void>((resolve) => {
+ releaseStart = resolve
+ })
+ const startEntered = new Promise<void>((resolve) => {
+ markStartEntered = resolve
+ })
+ const original = gateway.start
+ vi.spyOn(gateway, 'start').mockImplementation(async (options) => {
+ markStartEntered?.()
+ await gate
+ return await original(options)
+ })
+ const { manager, transport } = boot()
+ const pending = manager.connect(MachineId('m1'))
+ await startEntered
+ await manager.disconnect(MachineId('m1'))
+ releaseStart!()
+ await expect(pending).rejects.toMatchObject({ code: 'machine-connect-failed', message: /cancelled by disconnect/ })
+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')
+ expect(manager.link(MachineId('m1'))).toBeUndefined()
+ // 断开必须真的赢:成功路径不得把状态改写回 connected,也不得留下监听口或会话
+ expect(gateway.list()).toEqual([expect.objectContaining({ id: 'remote-outbound:m1', state: 'stopped', port: 0 })])
+ expect(transport.sessions[0]?.closed).toBe(true)
+ expect(transport.sessions[0]?.tunnelCloseCalls).toBe(1)
+ })
+
it('discards a tunnel failure that a disconnect superseded', async () => {
let releaseTunnel: ((error: Error) => void) | undefined
let markTunnelStarted: (() => void) | undefined
@@ -839,7 +1020,7 @@ describe('sshManager', () => {
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: (label: string, key: Buffer) => boolean | Promise<boolean>, _options: SshTransportOptions, _signal?: AbortSignal): Promise<SshSession> {
+ transport.connect = async function (this: FakeTransport, p: MachineProfile, verifier: (label: string, key: Buffer) => boolean | Promise<boolean>, _options: RemoteTransportOptions, _signal?: AbortSignal): Promise<RemoteSession> {
const accepted = await verifier(String(p.id), Buffer.from('other-key'))
if (!accepted)
throw new Error('Host key verification failed')
@@ -1040,7 +1221,7 @@ describe('sshManager install', () => {
// so the message is asserted on the caught error directly.
const failure = await manager.install(MachineId('m1')).then(
() => { throw new Error('expected a rejection') },
- error => error as SshError,
+ error => error as RemoteError,
)
expect(failure.code).toBe('machine-install-failed')
// No streaming tap answered, so the failure keeps the exit stderr.
@@ -1074,7 +1255,7 @@ describe('sshManager install', () => {
const { manager, events } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const failure = await manager.install(MachineId('m1')).then(
() => { throw new Error('expected a rejection') },
- error => error as SshError,
+ error => error as RemoteError,
)
expect(failure.code).toBe('machine-install-failed')
// The streamed log wins over the collected stdout/stderr.
@@ -1093,7 +1274,7 @@ describe('sshManager install', () => {
const { manager } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const failure = await manager.install(MachineId('m1')).then(
() => { throw new Error('expected a rejection') },
- error => error as SshError,
+ error => error as RemoteError,
)
expect(failure.message).toMatch(/install failed on remote \(exit 10\): .*所有下载源均失败/)
})
@@ -1107,7 +1288,7 @@ describe('sshManager install', () => {
const { manager, events } = boot({ sessionFactory: () => session })
const failure = await manager.install(MachineId('m1')).then(
() => { throw new Error('expected a rejection') },
- error => error as SshError,
+ error => error as RemoteError,
)
expect(failure.code).toBe('machine-install-failed')
expect(failure.message).toContain('cannot probe remote platform')
@@ -1137,7 +1318,7 @@ describe('sshManager install', () => {
const { manager, events } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const failure = await manager.install(MachineId('m1')).then(
() => { throw new Error('expected a rejection') },
- error => error as SshError,
+ error => error as RemoteError,
)
expect(failure.code).toBe('machine-install-failed')
expect(failure.message).toContain('timed out')
@@ -1247,7 +1428,7 @@ describe('sshManager install', () => {
releaseInstall!()
const failure = await pending.then(
() => { throw new Error('expected a rejection') },
- error => error as SshError,
+ error => error as RemoteError,
)
expect(failure.code).toBe('machine-install-failed')
expect(failure.message).toMatch(/install failed on remote/)
@@ -1278,7 +1459,7 @@ describe('sshManager install', () => {
code: 'machine-dsh-missing',
message: /entry .* is not present/,
})
- // The exception path (SshError, not a script exit) settles the stream too.
+ // The exception path (RemoteError, not a script exit) settles the stream too.
const terminals = terminalsOf(events)
expect(terminals).toHaveLength(1)
expect(terminals[0]).toMatchObject({ stage: 'failed', terminal: 'failed' })
@@ -1560,9 +1741,8 @@ describe('sshManager reconnect', () => {
expect(transport.connectCalls).toBe(1)
})
- it('publishes the tunnel URL with the launch token when the remote log has one', async () => {
- // 远端 web 日志带 token:隧道 URL 附带 ?token=(首次加载 mint 鉴权 cookie)
- const { manager } = boot({
+ it('keeps the launch token out of the link and reads it only when the gateway mints', async () => {
+ const { manager, transport } = boot({
sessionFactory: () => {
const session = new FakeSession(() => true)
session.webTokenResult = 'tok-abc-123\n'
@@ -1570,8 +1750,10 @@ describe('sshManager reconnect', () => {
},
})
const link = await manager.connect(MachineId('m1'))
- expect(link.tunnelBaseUrl).toBe('http://127.0.0.1:49152/?token=tok-abc-123')
- expect(manager.status(MachineId('m1')).tunnelBaseUrl).toBe('http://127.0.0.1:49152/?token=tok-abc-123')
+ expect(link.tunnelBaseUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/u)
+ expect(link.tunnelBaseUrl).not.toContain('tok-abc-123')
+ expect(JSON.stringify(manager.statuses())).not.toContain('tok-abc-123')
+ expect(transport.sessions[0]?.commands.some(command => command.startsWith('grep -oE \'token='))).toBe(false)
})
it('syncs the supplied plugin tree before ensuring the instance', async () => {
@@ -1583,8 +1765,8 @@ describe('sshManager reconnect', () => {
expect(session.commands.some(command => command.includes('PLUGINS_SYNCED'))).toBe(true)
const upload = session.options[session.commands.findIndex(command => command.includes('PLUGINS_SYNCED'))]?.stdinData
expect(upload).toBeInstanceOf(Buffer)
- const manifest = execFileSync('tar', ['-xOzf', '-', './dsh-tauri-ssh/package.json'], { input: upload, encoding: 'utf8' })
- expect(JSON.parse(manifest)).toEqual({ name: 'dsh-tauri-ssh', dsh: { bundle: {} } })
+ const manifest = execFileSync('tar', ['-xOzf', '-', './dsh-tauri-remote/package.json'], { input: upload, encoding: 'utf8' })
+ expect(JSON.parse(manifest)).toEqual({ name: 'dsh-tauri-remote', dsh: { bundle: {} } })
expect(events.since(MachineId('m1')).events.map(event => event.line).some(line => line.includes('捆绑插件已同步'))).toBe(true)
})
@@ -1602,39 +1784,300 @@ describe('sshManager reconnect', () => {
expect(lines.some(line => line.includes('捆绑插件同步失败'))).toBe(true)
})
- it('stamps the tunnel with the minted session cookie once the launch token resolves', async () => {
- const requests: string[] = []
- const server = createServer((request, response) => {
- requests.push(request.url ?? '')
- response.setHeader('set-cookie', ['dsh-auth-x=v1.signed; Path=/; HttpOnly'])
- response.end('ok')
- })
- await new Promise<void>((resolve) => {
- server.listen(0, '127.0.0.1', resolve)
- })
+ it('mints the DSH session cookie through the gateway on first access', async () => {
+ const standIn = await remoteStandIn()
+ try {
+ const { manager, transport } = boot({ sessionFactory: () => standInSession(standIn) })
+ const link = await manager.connect(MachineId('m1'))
+ // 连接阶段不铸造:网关只在首次访问时取用启动 token
+ expect(standIn.records).toEqual([])
+ const response = await getThrough(link.tunnelBaseUrl)
+ expect(response.status).toBe(200)
+ expect(response.body).toBe('dsh-ok')
+ expect(standIn.records.map(record => record.url)).toEqual(['/?token=tok-abc-123', '/'])
+ expect(standIn.records[0]?.host).toBe(`127.0.0.1:${new URL(link.tunnelBaseUrl).port}`)
+ expect(standIn.records[1]?.cookie).toBe('dsh-session=tok-abc-123')
+ expect(transport.sessions[0]?.closed).toBe(false)
+ }
+ finally {
+ await standIn.close()
+ }
+ })
+
+ it('re-reads the remote launch token to re-mint after the remote instance restarts', async () => {
+ const standIn = await remoteStandIn()
try {
- const port = (server.address() as AddressInfo).port
- const { manager, transport } = boot({
+ const { manager, transport } = boot({ sessionFactory: () => standInSession(standIn) })
+ const link = await manager.connect(MachineId('m1'))
+ expect((await getThrough(link.tunnelBaseUrl)).status).toBe(200)
+ // 远端实例重启:日志里的 token 变了,旧 cookie 随即失效
+ standIn.sessionCookie('dsh-session=tok-next-456')
+ transport.sessions[0]!.webTokenResult = 'tok-next-456\n'
+ const after = await getThrough(link.tunnelBaseUrl)
+ expect(after.status).toBe(200)
+ expect(after.body).toBe('dsh-ok')
+ expect(standIn.records.filter(record => record.url.startsWith('/?token=')).map(record => record.url)).toEqual(['/?token=tok-abc-123', '/?token=tok-next-456'])
+ expect(standIn.records.at(-1)?.cookie).toBe('dsh-session=tok-next-456')
+ expect(manager.link(MachineId('m1'))?.tunnelBaseUrl).toBe(link.tunnelBaseUrl)
+ }
+ finally {
+ await standIn.close()
+ }
+ })
+
+ it('declares identity and the gateway authority to the remote instance', async () => {
+ const standIn = await remoteStandIn()
+ try {
+ const { manager } = boot({
sessionFactory: () => {
const session = new FakeSession(() => true)
- session.webTokenResult = 'tok-abc-123\n'
- session.tunnelPort = port
+ session.tunnelPort = standIn.port
return session
},
})
const link = await manager.connect(MachineId('m1'))
- // mint 走隧道自身的带 token URL;注入槽随后携带 Cookie(iframe 免登录)
- expect(requests).toEqual(['/?token=tok-abc-123'])
- expect(transport.sessions[0]?.tunnelInjection?.cookie).toBe('dsh-auth-x=v1.signed')
- expect(link.tunnelBaseUrl).toBe(`http://127.0.0.1:${port}/?token=tok-abc-123`)
+ await getThrough(link.tunnelBaseUrl)
+ expect(standIn.records).toHaveLength(1)
+ expect(standIn.records[0]?.url).toBe('/')
+ expect(standIn.records[0]?.host).toBe(`127.0.0.1:${new URL(link.tunnelBaseUrl).port}`)
+ expect(standIn.records[0]?.encoding).toBe('identity')
}
finally {
- await new Promise<void>((resolve) => {
- server.close(() => resolve())
+ await standIn.close()
+ }
+ })
+
+ it('keeps the link alive when the remote launch token cannot be read, then mints on the next access', async () => {
+ const standIn = await remoteStandIn()
+ try {
+ const { manager, transport, events } = boot({
+ sessionFactory: () => {
+ const session = new FakeSession(() => true)
+ session.tunnelPort = standIn.port
+ return session
+ },
})
+ const link = await manager.connect(MachineId('m1'))
+ const denied = await getThrough(link.tunnelBaseUrl)
+ expect(denied.status).toBe(401)
+ expect(standIn.records.map(record => record.url)).toEqual(['/'])
+ expect(manager.status(MachineId('m1')).state).toBe('connected')
+ expect(manager.link(MachineId('m1'))?.tunnelBaseUrl).toBe(link.tunnelBaseUrl)
+ // 铸造失败必须留下一条可读事件:它是发现「远端实例重启」的唯一线索
+ expect(events.since(MachineId('m1')).events.map(event => event.line)).toContainEqual(
+ expect.stringContaining('DSH 原生 cookie 铸造失败(token 不可用)'),
+ )
+ // 失败的铸造不得被缓存:token 恢复后无需重连即可铸造成功
+ transport.sessions[0]!.webTokenResult = 'tok-abc-123\n'
+ const allowed = await getThrough(link.tunnelBaseUrl)
+ expect(allowed.status).toBe(200)
+ expect(allowed.body).toBe('dsh-ok')
+ expect(standIn.records.map(record => record.url)).toEqual(['/', '/?token=tok-abc-123', '/'])
+ }
+ finally {
+ await standIn.close()
}
})
+ it('runs one outbound gateway entry per connected machine, upstreamed at its tunnel port', async () => {
+ const { manager, transport } = boot()
+ const link = await manager.connect(MachineId('m1'))
+ expect(gateway.list()).toEqual([
+ expect.objectContaining({
+ id: 'remote-outbound:m1',
+ kind: 'outbound',
+ state: 'listening',
+ host: '127.0.0.1',
+ url: link.tunnelBaseUrl,
+ upstream: `http://127.0.0.1:${transport.sessions[0]!.tunnelPort}`,
+ }),
+ ])
+ await manager.disconnect(MachineId('m1'))
+ expect(gateway.list()).toEqual([expect.objectContaining({ id: 'remote-outbound:m1', state: 'stopped', port: 0 })])
+ expect(manager.status(MachineId('m1')).tunnelBaseUrl).toBeUndefined()
+ })
+
+ it('gives each connected machine its own gateway port', async () => {
+ const { manager } = boot()
+ const first = await manager.connect(MachineId('m1'))
+ const second = await manager.connect(MachineId('m2'))
+ expect(first.tunnelBaseUrl).not.toBe(second.tunnelBaseUrl)
+ expect(gateway.list().map(entry => entry.url).sort()).toEqual([first.tunnelBaseUrl, second.tunnelBaseUrl].sort())
+ })
+
+ it('does not report connected before the gateway entry is listening', async () => {
+ const { manager } = boot()
+ const original = gateway.start
+ const observed: string[] = []
+ const start = vi.spyOn(gateway, 'start').mockImplementation(async (options) => {
+ observed.push(manager.status(MachineId('m1')).state)
+ return await original(options)
+ })
+ const link = await manager.connect(MachineId('m1'))
+ expect(start).toHaveBeenCalledTimes(1)
+ expect(start.mock.calls[0]?.[0]).toMatchObject({ id: 'remote-outbound:m1', kind: 'outbound' })
+ expect(observed).toEqual(['connecting'])
+ expect(manager.status(MachineId('m1')).state).toBe('connected')
+ expect(manager.status(MachineId('m1')).tunnelBaseUrl).toBe(link.tunnelBaseUrl)
+ })
+
+ it('reuses the gateway port after a disconnect so the link survives a manual reconnect', async () => {
+ const { manager } = boot()
+ const first = await manager.connect(MachineId('m1'))
+ await manager.disconnect(MachineId('m1'))
+ const again = await manager.connect(MachineId('m1'))
+ expect(again.tunnelBaseUrl).toBe(first.tunnelBaseUrl)
+ })
+
+ it('dials the retry only after the previous gateway teardown has landed', async () => {
+ const order: string[] = []
+ const { manager, transport } = boot({
+ sessionFactory: () => {
+ order.push('dial')
+ return new FakeSession(() => true)
+ },
+ })
+ const first = await manager.connect(MachineId('m1'))
+ const original = gateway.stop
+ let release: () => void = () => {}
+ const gate = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ vi.spyOn(gateway, 'stop').mockImplementation(async (id) => {
+ order.push('teardown')
+ await gate
+ await original(id)
+ order.push('teardown-done')
+ })
+ transport.sessions[0]!.drop()
+ const due = machineStates.get(MachineId('m1'))!.reconnect?.nextRetryAt
+ expect(due).toBeTypeOf('number')
+ // 退避已到期(+50ms 余量)而回收仍未落地:此刻不许再拨号
+ await until(() => Date.now() > (due ?? 0) + 50, 'retry window passed')
+ expect(order).toEqual(['dial', 'teardown'])
+ release()
+ await until(() => manager.status(MachineId('m1')).state === 'connected', 'reconnect after teardown')
+ expect(order).toEqual(['dial', 'teardown', 'teardown-done', 'dial'])
+ expect(manager.link(MachineId('m1'))?.tunnelBaseUrl).toBe(first.tunnelBaseUrl)
+ })
+
+ it('reconnects when the gateway entry dies behind the machine', async () => {
+ const standIn = await remoteStandIn()
+ try {
+ const { manager } = boot({ sessionFactory: () => standInSession(standIn) })
+ const first = await manager.connect(MachineId('m1'))
+ await gateway.stop('remote-outbound:m1')
+ await until(() => manager.status(MachineId('m1')).state === 'reconnecting', 'reconnecting after gateway stop')
+ await until(() => manager.status(MachineId('m1')).state === 'connected', 'gateway restart')
+ expect(manager.link(MachineId('m1'))?.tunnelBaseUrl).toBe(first.tunnelBaseUrl)
+ expect((await getThrough(first.tunnelBaseUrl)).status).toBe(200)
+ }
+ finally {
+ await standIn.close()
+ }
+ })
+
+ it('keeps the link through a per-request upstream failure and serves again once the instance is back', async () => {
+ const standIn = await remoteStandIn()
+ let instanceAlive = true
+ const hop = await hopThrough(standIn.port, () => instanceAlive)
+ const { manager, transport, events } = boot({
+ sessionFactory: () => {
+ const session = standInSession(standIn)
+ session.tunnelPort = hop.port
+ return session
+ },
+ })
+ try {
+ const link = await manager.connect(MachineId('m1'))
+ // 远端实例停机而隧道口(hop)仍在监听:只有转发到实例的那一跳失败
+ instanceAlive = false
+ const denied = await getThrough(link.tunnelBaseUrl)
+ expect(denied.status).toBe(502)
+ expect(denied.body).toContain('上游不可达')
+ // 死的是远端实例而不是链路:SSH 会话与入口都不得被拆掉
+ expect(transport.sessions[0]?.closed).toBe(false)
+ expect(gateway.list()).toEqual([expect.objectContaining({ id: 'remote-outbound:m1', state: 'listening' })])
+ expect(manager.status(MachineId('m1')).state).toBe('connected')
+ expect(manager.link(MachineId('m1'))?.tunnelBaseUrl).toBe(link.tunnelBaseUrl)
+ await until(() => (manager.status(MachineId('m1')).lastError ?? '').includes('上游不可达'), 'readable per-request failure')
+ expect(events.since(MachineId('m1')).events.some(event => event.line.includes('上游不可达'))).toBe(true)
+ // 实例原地恢复即恢复服务,无需任何重连
+ instanceAlive = true
+ const served = await getThrough(link.tunnelBaseUrl)
+ expect(served.status).toBe(200)
+ expect(served.body).toBe('dsh-ok')
+ expect(manager.status(MachineId('m1')).state).toBe('connected')
+ }
+ finally {
+ await standIn.close()
+ await hop.close()
+ }
+ })
+
+ it('reconnects when the upstream tunnel dies behind the gateway', async () => {
+ let standIn = await remoteStandIn()
+ const port = standIn.port
+ const { manager } = boot({ sessionFactory: () => standInSession(standIn) })
+ try {
+ const link = await manager.connect(MachineId('m1'))
+ // 隧道口本身消失:同一端口不再有监听,网关转发与链路探测都拿到 ECONNREFUSED
+ await standIn.close()
+ const response = await getThrough(link.tunnelBaseUrl)
+ expect(response.status).toBe(502)
+ expect(response.body).toContain('上游不可达')
+ await until(() => manager.status(MachineId('m1')).state === 'reconnecting', 'reconnecting after upstream kill')
+ standIn = await remoteStandIn(port)
+ await until(() => manager.status(MachineId('m1')).state === 'connected', 'reconnect after upstream kill')
+ expect(manager.status(MachineId('m1')).state).toBe('connected')
+ expect((await getThrough(manager.link(MachineId('m1'))!.tunnelBaseUrl)).status).toBe(200)
+ }
+ finally {
+ await standIn.close()
+ }
+ })
+
+ it('gives up with a readable reason when every gateway candidate port is taken', async () => {
+ const { manager, transport } = boot()
+ const first = await manager.connect(MachineId('m1'))
+ const remembered = Number(new URL(first.tunnelBaseUrl).port)
+ await manager.disconnect(MachineId('m1'))
+ const range = await occupyRange(GATEWAY_CANDIDATES, remembered)
+ machineStates.get(MachineId('m1'))!.preferredGatewayPort = range.base
+ try {
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })
+ const status = manager.status(MachineId('m1'))
+ expect(status.state).toBe('given-up')
+ expect(status.lastError).toMatch(/网关端口全部占用/u)
+ expect(status.nextRetryAt).toBeUndefined()
+ expect(manager.link(MachineId('m1'))).toBeUndefined()
+ expect(transport.sessions.at(-1)?.closed).toBe(true)
+ expect(transport.sessions.at(-1)?.tunnelCloseCalls).toBe(1)
+ }
+ finally {
+ await closeServers(range.servers)
+ }
+ })
+
+ it('rebuilds the outbound entry after a full gateway teardown', async () => {
+ const { manager } = boot()
+ const first = await manager.connect(MachineId('m1'))
+ await gateway.dispose()
+ expect(gateway.list()).toEqual([])
+ await until(() => manager.status(MachineId('m1')).state === 'reconnecting', 'reconnecting after gateway teardown')
+ await until(() => manager.status(MachineId('m1')).state === 'connected', 'gateway rebuilt')
+ expect(gateway.list()).toEqual([expect.objectContaining({ id: 'remote-outbound:m1', kind: 'outbound', state: 'listening' })])
+ expect(manager.link(MachineId('m1'))?.tunnelBaseUrl).toBe(first.tunnelBaseUrl)
+ })
+
+ it('closes the gateway when the machine profile vanishes', async () => {
+ const { manager } = boot()
+ await manager.connect(MachineId('m1'))
+ manager.refreshProfiles(new Map([[secondProfile.id, secondProfile]]))
+ await until(() => gateway.list().every(entry => entry.state === 'stopped'), 'gateway teardown')
+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')
+ })
+
it('exits given-up on a fresh connect', async () => {
let fail = true
const factory = (): FakeSession => fail ? refused() : new FakeSession(() => true)
@@ -1644,7 +2087,7 @@ describe('sshManager reconnect', () => {
expect(manager.status(MachineId('m1')).state).toBe('given-up')
fail = false
const link = await manager.connect(MachineId('m1'))
- expect(link.tunnelBaseUrl).toBe('http://127.0.0.1:49152')
+ expect(link.tunnelBaseUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/u)
expect(manager.status(MachineId('m1')).state).toBe('connected')
})
@@ -1724,3 +2167,41 @@ describe('sshManager reconnect', () => {
expect(manager.status(MachineId('m1')).state).toBe('disconnected')
})
})
+
+describe('transport capability branches', () => {
+ it('answers test() with a disabled message instead of dialing when the transport cannot exec', async () => {
+ const { manager, transport } = boot({ capabilities: { exec: false } })
+ await expect(manager.test(MachineId('m1'))).resolves.toEqual({ ok: false, message: expect.stringContaining('cannot exec') })
+ expect(transport.connectCalls).toBe(0)
+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')
+ })
+
+ it('rejects connect() without dialing or scheduling a reconnect when the transport cannot exec', async () => {
+ const { manager, transport } = boot({ capabilities: { exec: false } })
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-transport-unsupported' })
+ expect(transport.connectCalls).toBe(0)
+ expect(machineStates.get(MachineId('m1'))?.reconnect).toBeUndefined()
+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')
+ })
+
+ it('rejects connect() when the transport declares exec but cannot stream', async () => {
+ const { manager, transport } = boot({ capabilities: { stream: false } })
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-transport-unsupported', message: expect.stringContaining('cannot stream') })
+ expect(transport.connectCalls).toBe(0)
+ expect(machineStates.get(MachineId('m1'))?.reconnect).toBeUndefined()
+ })
+
+ it('rejects install() and openSession() when the transport cannot exec', async () => {
+ const { manager, transport } = boot({ capabilities: { exec: false } })
+ await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-transport-unsupported' })
+ await expect(manager.openSession(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-transport-unsupported' })
+ expect(transport.connectCalls).toBe(0)
+ })
+
+ it('still connects when the transport declares both capabilities', async () => {
+ const { manager, transport } = boot()
+ await manager.connect(MachineId('m1'))
+ expect(transport.connectCalls).toBe(1)
+ expect(manager.status(MachineId('m1')).state).toBe('connected')
+ })
+})
diff --git a/packages/dsh-tauri-ssh/src/host/service/machine.ts b/packages/dsh-tauri-remote/src/host/service/machine.ts
similarity index 70%
rename from packages/dsh-tauri-ssh/src/host/service/machine.ts
rename to packages/dsh-tauri-remote/src/host/service/machine.ts
index 62a685fa..54de3dad 100644
--- a/packages/dsh-tauri-ssh/src/host/service/machine.ts
+++ b/packages/dsh-tauri-remote/src/host/service/machine.ts
@@ -1,26 +1,33 @@
import type { Buffer } from 'node:buffer'
-import type { MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, SshInstallResult, SshLink, SshMachineStatus, SshProgress, SshSession, SshTestResult, TunnelHeaderInjection } from '../types/index'
+import type { ClientRequest } from 'node:http'
+import type { MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, RemoteInstallResult, RemoteLink, RemoteMachineStatus, RemoteProgress, RemoteSession, RemoteStreamHandle, RemoteTestResult } from '../types/index'
import type { WorkspaceAllowlist } from '../utils/allowlist'
import type { SshHostBlock } from '../utils/ssh-config'
import type { BootstrapHooks } from './bootstrap.types'
import type { MachineState, ReconnectState } from './machine.types'
+import type { RemoteTransportCapabilities } from './transport.types'
+import { request } from 'node:http'
import { defineService } from 'dsh-tauri'
import { join } from 'pathe'
import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
import { messageOf } from '../../shared/error'
-import { REMOTE_ROOT } from '../config/constants'
+import { DEFAULT_MACHINE_TRANSPORT, REMOTE_ROOT } from '../config/constants'
import { harnessHome, homeDirPath, hostConfig, machineProfiles, machineRuntimeDeps, machineStates, machineTable, sshDirPath } from '../config/runtime'
-import { MachineId, SshError } from '../types/index'
+import { MachineId, RemoteError } from '../types/index'
import { carryWorkspaceAllowlist } from '../utils/allowlist'
import { syncBundledPlugins } from '../utils/plugins-sync'
import { discoverableHosts, loadSshConfigBlocks, lookupSshConfig, resolveSshAuth } from '../utils/ssh-config'
import { bootstrap } from './bootstrap'
import { checkMissingCommand, credentialsCopyCommand, describeExecFailure, ensurePnpmCommand, firstLineOf, missingComponentsOf, planRemoteInstall, readEnvCredentials, remoteWebTokenCommand, safeProfileName, skippedVerificationSummary } from './bootstrap.utils'
import { events } from './events'
+import { gateway } from './gateway'
import { knownHosts } from './known-hosts'
import { fingerprintHostKey } from './known-hosts.utils'
import { state } from './state'
-import { mintTunnelCookie } from './transport.utils'
+
+const TUNNEL_PROBE_TIMEOUT_MS = 2_000
+
+const GATEWAY_PORTS_EXHAUSTED = 'ERR_GATEWAY_PORTS_EXHAUSTED'
export const machine = defineService({
enabled(): boolean {
@@ -69,7 +76,7 @@ export const machine = defineService({
return [...discoveredProfiles(blocks, manual).values()].map(profileView)
},
- statuses(): SshMachineStatus[] {
+ statuses(): RemoteMachineStatus[] {
return [...machineProfiles.keys()].map(id => machine.status(id))
},
@@ -81,7 +88,7 @@ export const machine = defineService({
return safeProfileName(machineProfiles.get(machineId)?.profileName)
},
- setProgress(machineId: MachineId, progress?: SshProgress): void {
+ setProgress(machineId: MachineId, progress?: RemoteProgress): void {
const target = ensureState(machineId)
if (progress === undefined)
delete target.progress
@@ -90,7 +97,7 @@ export const machine = defineService({
emit(machineId)
},
- status(machineId: MachineId): SshMachineStatus {
+ status(machineId: MachineId): RemoteMachineStatus {
const target = machineStates.get(machineId)
const lastError = target?.lastError
const progress = target?.progress
@@ -108,12 +115,14 @@ export const machine = defineService({
}
},
- link(machineId: MachineId): SshLink | undefined {
+ link(machineId: MachineId): RemoteLink | undefined {
return machineStates.get(machineId)?.link
},
- async test(machineId: MachineId, signal?: AbortSignal): Promise<SshTestResult> {
+ async test(machineId: MachineId, signal?: AbortSignal): Promise<RemoteTestResult> {
const profile = requireProfile(machineId)
+ if (!transportCapabilities(profile).exec)
+ return { ok: false, message: unsupportedCapabilityMessage(profile, 'exec') }
const target = ensureState(machineId)
const previousPhase = target.phase
target.phase = 'testing'
@@ -127,7 +136,7 @@ export const machine = defineService({
}
emit(machineId)
}
- let session: SshSession
+ let session: RemoteSession
try {
session = await openTransportSession(profile, signal)
}
@@ -150,8 +159,9 @@ export const machine = defineService({
}
},
- async connect(machineId: MachineId, signal?: AbortSignal): Promise<SshLink> {
+ async connect(machineId: MachineId, signal?: AbortSignal): Promise<RemoteLink> {
const profile = requireProfile(machineId)
+ requireCapabilities(machineId, profile, ['exec', 'stream'])
const target = ensureState(machineId)
if (target.link !== undefined)
return target.link
@@ -160,6 +170,7 @@ export const machine = defineService({
target.phase = 'connecting'
delete target.lastError
delete target.dshMissing
+ delete target.gatewayExhausted
target.progress = { phase: 'handshake' }
emit(machineId)
const generation = target.generation
@@ -171,7 +182,7 @@ export const machine = defineService({
const current = machineStates.get(machineId)
if (current === undefined || current.generation !== generation)
return
- if ((error instanceof SshError && error.code === 'machine-dsh-missing') || current.dshMissing === true) {
+ if (terminalConnectFailure(error, current)) {
giveUp(machineId, current)
return
}
@@ -181,8 +192,9 @@ export const machine = defineService({
return target.connecting
},
- async openSession(machineId: MachineId, signal?: AbortSignal): Promise<SshSession> {
+ async openSession(machineId: MachineId, signal?: AbortSignal): Promise<RemoteSession> {
const profile = requireProfile(machineId)
+ requireCapabilities(machineId, profile, ['exec'])
refuseWhileReconnecting(machineId, ensureState(machineId))
return await openTransportSession(profile, signal)
},
@@ -195,13 +207,20 @@ export const machine = defineService({
stopReconnect(target)
delete target.lastError
delete target.dshMissing
+ delete target.gatewayExhausted
delete target.progress
+ const entry = target.gateway
const tunnel = target.tunnel
const session = target.session
+ delete target.gateway
delete target.tunnel
delete target.session
delete target.link
target.phase = 'disconnected'
+ if (entry !== undefined) {
+ entry.unsubscribe()
+ await gateway.stop(entry.id).catch(() => undefined)
+ }
if (tunnel !== undefined)
await tunnel.close().catch(() => undefined)
if (session !== undefined)
@@ -213,8 +232,9 @@ export const machine = defineService({
await Promise.all([...machineStates.keys()].map(id => machine.disconnect(id)))
},
- async install(machineId: MachineId, signal?: AbortSignal): Promise<SshInstallResult> {
+ async install(machineId: MachineId, signal?: AbortSignal): Promise<RemoteInstallResult> {
const profile = requireProfile(machineId)
+ requireCapabilities(machineId, profile, ['exec'])
const target = ensureState(machineId)
refuseWhileReconnecting(machineId, target)
if (target.installing === undefined) {
@@ -318,10 +338,26 @@ function discoveredProfiles(blocks: SshHostBlock[], manual: Map<MachineId, Machi
function requireProfile(machineId: MachineId): MachineProfile {
const profile = machineProfiles.get(machineId)
if (profile === undefined)
- throw new SshError('machine-not-found', machineId, `no SSH machine profile "${machineId}"`)
+ throw new RemoteError('machine-not-found', machineId, `no SSH machine profile "${machineId}"`)
return profile
}
+function transportCapabilities(profile: MachineProfile): RemoteTransportCapabilities {
+ return machineRuntimeDeps().transport.resolve(profile).capabilities
+}
+
+function unsupportedCapabilityMessage(profile: MachineProfile, capability: keyof RemoteTransportCapabilities): string {
+ return `transport "${profile.transport ?? DEFAULT_MACHINE_TRANSPORT}" cannot ${capability} on this machine`
+}
+
+function requireCapabilities(machineId: MachineId, profile: MachineProfile, required: readonly (keyof RemoteTransportCapabilities)[]): void {
+ const capabilities = transportCapabilities(profile)
+ for (const capability of required) {
+ if (!capabilities[capability])
+ throw new RemoteError('machine-transport-unsupported', machineId, unsupportedCapabilityMessage(profile, capability))
+ }
+}
+
function ensureState(machineId: MachineId): MachineState {
let target = machineStates.get(machineId)
if (target === undefined) {
@@ -331,10 +367,10 @@ function ensureState(machineId: MachineId): MachineState {
return target
}
-async function openTransportSession(profile: MachineProfile, signal?: AbortSignal): Promise<SshSession> {
+async function openTransportSession(profile: MachineProfile, signal?: AbortSignal): Promise<RemoteSession> {
const deps = machineRuntimeDeps()
const config = hostConfig()
- return await deps.transport.connect(
+ return await deps.transport.resolve(profile).connect(
profile,
(label, key) => checkHostKey(MachineId(label), key),
{
@@ -347,7 +383,7 @@ async function openTransportSession(profile: MachineProfile, signal?: AbortSigna
)
}
-async function readRemoteWebToken(session: SshSession): Promise<string | undefined> {
+async function readRemoteWebToken(session: RemoteSession): Promise<string | undefined> {
try {
const result = await session.exec(remoteWebTokenCommand())
const token = result.stdout.trim()
@@ -372,10 +408,11 @@ async function checkHostKey(machineId: MachineId, hostKey: Buffer): Promise<bool
class AttemptCancelled extends Error {}
-async function performConnect(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshLink> {
+async function performConnect(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<RemoteLink> {
const target = ensureState(machineId)
const generation = target.generation
let bootstrapSettled = false
+ let portExhausted = false
const onEvent = settlingEventSink(machineId, () => {
bootstrapSettled = true
})
@@ -421,24 +458,61 @@ async function performConnect(machineId: MachineId, profile: MachineProfile, sig
onEvent,
},
)
- const injection: TunnelHeaderInjection = { cookie: undefined }
- const tunnel = await session.openTunnel(profile.remotePort, target.preferredTunnelPort, injection)
+ const tunnel = await session.stream(profile.remotePort, target.preferredTunnelPort)
if (generation !== target.generation) {
await tunnel.close().catch(() => undefined)
throw new AttemptCancelled()
}
- const webToken = await readRemoteWebToken(session)
- if (webToken !== undefined)
- injection.cookie = await mintTunnelCookie(`http://127.0.0.1:${tunnel.localPort}/?token=${webToken}`)
- const link: SshLink = {
- machineId,
- tunnelBaseUrl: `http://127.0.0.1:${tunnel.localPort}${webToken === undefined ? '' : `/?token=${webToken}`}`,
+ const entryId = outboundEntryId(machineId)
+ let entryPort: number
+ try {
+ const entry = await gateway.start({
+ id: entryId,
+ kind: 'outbound',
+ upstream: `http://127.0.0.1:${tunnel.localPort}`,
+ port: target.preferredGatewayPort ?? 0,
+ tokenProvider: async (authority) => {
+ const token = await readRemoteWebToken(session)
+ return token === undefined ? undefined : `http://${authority}/?token=${token}`
+ },
+ })
+ if (generation !== target.generation) {
+ await cancelAttempt(entryId, tunnel)
+ throw new AttemptCancelled()
+ }
+ entryPort = entry.port
+ }
+ catch (error) {
+ if (!(error instanceof AttemptCancelled)) {
+ await tunnel.close().catch(() => undefined)
+ portExhausted = isGatewayPortExhausted(error)
+ }
+ throw error
}
+ const unsubscribe = gateway.subscribe((event) => {
+ if (event.id !== entryId || (event.kind !== 'stopped' && event.kind !== 'upstream' && event.kind !== 'cookie' && event.kind !== 'compression'))
+ return
+ if (machineStates.get(machineId)?.tunnel !== tunnel)
+ return
+ // 铸造 / 压缩失败只留可读事件:单条请求的降级不该改写 link 级状态
+ if (event.kind === 'cookie' || event.kind === 'compression') {
+ events.append(machineId, 'reconnect', redacted(machineId, `网关转发异常:${event.line}`))
+ return
+ }
+ // 本回调与网关写回下游响应同处一条调用链:必须让当前响应先出网,否则拆除会截断响应体。
+ const dead = event.kind === 'stopped'
+ setImmediate(() => {
+ void gatewayFailure(machineId, tunnel, event.line, dead)
+ })
+ })
+ const link: RemoteLink = { machineId, tunnelBaseUrl: `http://127.0.0.1:${entryPort}` }
const reconnected = target.reconnect !== undefined ? target.reconnect.reasons.length : undefined
target.session = session
target.tunnel = tunnel
+ target.gateway = { id: entryId, unsubscribe }
target.link = link
target.preferredTunnelPort = tunnel.localPort
+ target.preferredGatewayPort = entryPort
if (session.authMethod === undefined)
delete target.authMethod
else
@@ -447,17 +521,9 @@ async function performConnect(machineId: MachineId, profile: MachineProfile, sig
stopReconnect(target)
target.phase = 'connected'
session.onClosed(() => {
- const current = machineStates.get(machineId)
- if (current?.session !== session)
+ if (machineStates.get(machineId)?.session !== session)
return
- const dropped = current.tunnel
- delete current.session
- delete current.tunnel
- delete current.link
- delete current.progress
- void dropped?.close().catch(() => undefined)
- current.lastError = 'SSH connection closed'
- beginReconnect(machineId)
+ detach(machineId, 'SSH connection closed')
})
emit(machineId)
events.append(
@@ -479,20 +545,101 @@ async function performConnect(machineId: MachineId, profile: MachineProfile, sig
catch (error) {
await session.close().catch(() => undefined)
if (error instanceof AttemptCancelled)
- throw new SshError('machine-connect-failed', machineId, 'connection cancelled by disconnect')
+ throw new RemoteError('machine-connect-failed', machineId, 'connection cancelled by disconnect')
const message = redacted(machineId, messageOf(error))
if (generation === target.generation && !bootstrapSettled)
onEvent('failed', 'bootstrap 失败', { terminal: 'failed', reason: message })
if (generation === target.generation) {
delete target.progress
noteConnectFailure(machineId, message)
+ if (portExhausted)
+ target.gatewayExhausted = true
target.phase = 'disconnected'
emit(machineId)
}
- throw new SshError('machine-bootstrap-failed', machineId, message)
+ throw new RemoteError('machine-bootstrap-failed', machineId, message)
}
}
+function outboundEntryId(machineId: MachineId): string {
+ return `remote-outbound:${machineId}`
+}
+
+async function cancelAttempt(entryId: string, tunnel: RemoteStreamHandle): Promise<void> {
+ await Promise.all([
+ gateway.stop(entryId).catch(() => undefined),
+ tunnel.close().catch(() => undefined),
+ ])
+}
+
+/**
+ * 网关的 `upstream` 是**逐请求**错误通道(超时 504 / 不可达 502),不是链路级死亡通知;只有入口自身停止
+ * (`dead`)或回环隧道口不再接受连接才说明链路丢了。探测把这两种情况分开,否则一条慢请求的 504 就会
+ * 换掉整条 SSH 会话与 iframe,远端实例重启窗口内的 502 也会被误判成入口死亡。
+ */
+async function gatewayFailure(machineId: MachineId, tunnel: RemoteStreamHandle, line: string, dead: boolean): Promise<void> {
+ const target = machineStates.get(machineId)
+ if (target === undefined || target.tunnel !== tunnel)
+ return
+ if (!dead && !await tunnelRefused(tunnel.localPort)) {
+ recordGatewayIncident(machineId, `网关转发失败:${line}`)
+ return
+ }
+ detach(machineId, `网关入口异常退出:${line}`)
+}
+
+/** 直连隧道口:只有本机回环上的 ECONNREFUSED 才等于「隧道口不再监听」;转发腿上的复位与超时都算隧道仍在。 */
+function tunnelRefused(port: number): Promise<boolean> {
+ return new Promise((resolve) => {
+ const request = probeRequest(port)
+ const timer = setTimeout(() => {
+ request.destroy()
+ resolve(false)
+ }, TUNNEL_PROBE_TIMEOUT_MS)
+ const settle = (refused: boolean): void => {
+ clearTimeout(timer)
+ resolve(refused)
+ }
+ request.on('response', (response) => {
+ response.resume()
+ settle(false)
+ })
+ request.on('error', (error) => {
+ settle(codeOf(error) === 'ECONNREFUSED')
+ })
+ request.end()
+ })
+}
+
+function probeRequest(port: number): ClientRequest {
+ return request({ host: '127.0.0.1', port, method: 'HEAD', path: '/', agent: false, headers: { connection: 'close' } })
+}
+
+function recordGatewayIncident(machineId: MachineId, reason: string): void {
+ const target = machineStates.get(machineId)
+ if (target === undefined)
+ return
+ target.lastError = redacted(machineId, reason)
+ events.append(machineId, 'reconnect', target.lastError)
+ emit(machineId)
+}
+
+function codeOf(error: unknown): string | undefined {
+ return (error as NodeJS.ErrnoException | null)?.code
+}
+
+/** 网关端口耗尽的判据:内核只在「候选全被登记表占用」或「每个候选都撞上 EADDRINUSE」时抛出,无人重试能改变这一点。 */
+function isGatewayPortExhausted(error: unknown): boolean {
+ const code = codeOf(error)
+ return code === 'EADDRINUSE' || code === GATEWAY_PORTS_EXHAUSTED
+}
+
+function terminalConnectFailure(error: unknown, target: MachineState): boolean {
+ if (target.dshMissing === true || target.gatewayExhausted === true)
+ return true
+ return error instanceof RemoteError && error.code === 'machine-dsh-missing'
+}
+
function noteConnectFailure(machineId: MachineId, message: string): void {
const target = machineStates.get(machineId)
if (target === undefined)
@@ -504,14 +651,43 @@ function noteConnectFailure(machineId: MachineId, message: string): void {
events.append(machineId, 'auth', redactedMessage)
}
-function beginReconnect(machineId: MachineId): void {
+function detach(machineId: MachineId, reason: string): void {
+ const target = machineStates.get(machineId)
+ if (target === undefined)
+ return
+ const entry = target.gateway
+ const tunnel = target.tunnel
+ const session = target.session
+ delete target.gateway
+ delete target.session
+ delete target.tunnel
+ delete target.link
+ delete target.progress
+ target.lastError = redacted(machineId, reason)
+ if (entry !== undefined)
+ entry.unsubscribe()
+ const pending = Promise.all([
+ entry === undefined ? undefined : gateway.stop(entry.id).catch(() => undefined),
+ tunnel === undefined ? undefined : tunnel.close().catch(() => undefined),
+ session === undefined ? undefined : session.close().catch(() => undefined),
+ ]).then(() => undefined)
+ beginReconnect(machineId, pending)
+}
+
+function beginReconnect(machineId: MachineId, pending?: Promise<void>): void {
const target = ensureState(machineId)
- if (target.reconnect !== undefined)
+ if (target.reconnect !== undefined) {
+ if (pending !== undefined) {
+ const previous = target.reconnect.pending
+ target.reconnect.pending = previous === undefined ? pending : Promise.all([previous, pending]).then(() => undefined)
+ }
return
+ }
target.reconnect = {
generation: target.generation,
attempt: 0,
reasons: [target.lastError ?? 'connection failed'],
+ ...pending === undefined ? {} : { pending },
}
scheduleReconnect(machineId)
}
@@ -551,8 +727,16 @@ async function attemptReconnect(machineId: MachineId, expected: ReconnectState):
const profile = machineProfiles.get(machineId)
if (profile === undefined)
return
+ const pending = rec.pending
+ delete rec.pending
+ if (pending !== undefined)
+ await pending
+ const current = machineStates.get(machineId)
+ const active = current?.reconnect
+ if (current === undefined || active !== rec || rec.generation !== current.generation)
+ return
delete rec.nextRetryAt
- target.progress = { phase: 'handshake' }
+ current.progress = { phase: 'handshake' }
emit(machineId)
try {
await performConnect(machineId, profile)
@@ -560,15 +744,15 @@ async function attemptReconnect(machineId: MachineId, expected: ReconnectState):
catch (error) {
if (error instanceof AttemptCancelled)
return
- const current = machineStates.get(machineId)
- const loop = current?.reconnect
- if (current === undefined || loop === undefined || loop.generation !== current.generation)
+ const after = machineStates.get(machineId)
+ const loop = after?.reconnect
+ if (after === undefined || loop !== rec || rec.generation !== after.generation)
return
- if ((error instanceof SshError && error.code === 'machine-dsh-missing') || current.dshMissing === true) {
- giveUp(machineId, current)
+ if (terminalConnectFailure(error, after)) {
+ giveUp(machineId, after)
return
}
- loop.reasons.push(current.lastError ?? describeSshFailure(error))
+ loop.reasons.push(after.lastError ?? describeSshFailure(error))
scheduleReconnect(machineId)
}
}
@@ -596,7 +780,7 @@ function refuseWhileReconnecting(machineId: MachineId, target: MachineState): vo
const rec = target.reconnect
if (rec === undefined)
return
- throw new SshError(
+ throw new RemoteError(
'machine-reconnecting',
machineId,
`machine is reconnecting (attempt ${rec.attempt} of ${hostConfig().reconnectMaxAttempts}); `
@@ -614,7 +798,7 @@ function redacted(machineId: MachineId, text: string): string {
return out
}
-async function performInstall(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshInstallResult> {
+async function performInstall(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<RemoteInstallResult> {
const config = hostConfig()
const target = ensureState(machineId)
const generation = target.generation
@@ -655,7 +839,7 @@ async function performInstall(machineId: MachineId, profile: MachineProfile, sig
const entryCheck = await session.exec(`test -f ${dshExpr} && printf '%s\\n' ${dshExpr}`)
const dshPath = firstLineOf(entryCheck.stdout)
if (entryCheck.code !== 0 || dshPath === '') {
- throw new SshError(
+ throw new RemoteError(
'machine-dsh-missing',
machineId,
`dsh install finished on "${profile.host}" but the entry ${dshExpr} is not present`,
@@ -692,7 +876,7 @@ async function performInstall(machineId: MachineId, profile: MachineProfile, sig
catch (error) {
await session.close().catch(() => undefined)
if (error instanceof AttemptCancelled)
- throw new SshError('machine-install-failed', machineId, 'install cancelled by disconnect')
+ throw new RemoteError('machine-install-failed', machineId, 'install cancelled by disconnect')
const message = redacted(machineId, messageOf(error))
if (generation === target.generation && !settled)
onEvent('failed', 'install 失败', { terminal: 'failed', reason: message })
@@ -702,13 +886,13 @@ async function performInstall(machineId: MachineId, profile: MachineProfile, sig
target.phase = 'disconnected'
emit(machineId)
}
- if (error instanceof SshError)
+ if (error instanceof RemoteError)
throw error
- throw new SshError('machine-install-failed', machineId, message)
+ throw new RemoteError('machine-install-failed', machineId, message)
}
}
-async function copyCredentials(session: SshSession): Promise<boolean> {
+async function copyCredentials(session: RemoteSession): Promise<boolean> {
const credentials = readEnvCredentials(join(harnessHome(), '.env'))
const apiKey = credentials.apiKey
if (apiKey === undefined)
@@ -748,7 +932,7 @@ async function openSessionOrFail(
profile: MachineProfile,
signal?: AbortSignal,
onFail?: () => void,
-): Promise<SshSession> {
+): Promise<RemoteSession> {
const target = ensureState(machineId)
const generation = target.generation
try {
@@ -761,7 +945,7 @@ async function openSessionOrFail(
noteConnectFailure(machineId, message)
onFail?.()
}
- throw new SshError('machine-connect-failed', machineId, message)
+ throw new RemoteError('machine-connect-failed', machineId, message)
}
}
diff --git a/packages/dsh-tauri-remote/src/host/service/machine.types.ts b/packages/dsh-tauri-remote/src/host/service/machine.types.ts
new file mode 100644
index 00000000..ad1cd685
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/machine.types.ts
@@ -0,0 +1,54 @@
+import type {
+ MachineId,
+ RemoteAuthMethod,
+ RemoteInstallResult,
+ RemoteLink,
+ RemoteMachineStatus,
+ RemoteProgress,
+ RemoteSession,
+ RemoteStreamHandle,
+} from '../types/index'
+import type { WorkspaceAllowlist } from '../utils/allowlist'
+import type { BundledPluginsTree } from '../utils/plugins-sync'
+import type { RemoteTransportResolver } from './transport.types'
+
+export interface MachineGatewayHandle {
+ id: string
+ unsubscribe: () => void
+}
+
+export interface MachineState {
+ generation: number
+ phase: 'disconnected' | 'testing' | 'connecting' | 'connected' | 'reconnecting' | 'given-up'
+ connecting?: Promise<RemoteLink>
+ installing?: Promise<RemoteInstallResult>
+ session?: RemoteSession
+ tunnel?: RemoteStreamHandle
+ gateway?: MachineGatewayHandle
+ link?: RemoteLink
+ lastError?: string
+ dshMissing?: boolean
+ gatewayExhausted?: boolean
+ progress?: RemoteProgress
+ reconnect?: ReconnectState
+ preferredTunnelPort?: number
+ preferredGatewayPort?: number
+ authMethod?: RemoteAuthMethod
+}
+
+export interface ReconnectState {
+ generation: number
+ attempt: number
+ nextRetryAt?: number
+ timer?: NodeJS.Timeout
+ /** 上一次连接(会话 / 隧道 / 网关入口)的回收:下一次拨号必须等它落地,端口才可能被原样复用。 */
+ pending?: Promise<void>
+ reasons: string[]
+}
+
+export interface MachineDeps {
+ transport: RemoteTransportResolver
+ emitStatus: (machineId: MachineId, status: RemoteMachineStatus) => void
+ localAllowlist: () => WorkspaceAllowlist
+ bundledPluginsTree?: BundledPluginsTree
+}
diff --git a/packages/dsh-tauri-remote/src/host/service/pairing.test.ts b/packages/dsh-tauri-remote/src/host/service/pairing.test.ts
new file mode 100644
index 00000000..3eeb6d27
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/pairing.test.ts
@@ -0,0 +1,128 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { tokenMatches } from '../utils/auth'
+import { consumePairingCode, PAIRING_TTL_MS, pairingCodeOf, resetPairingCode, waitForPairingUse } from './pairing'
+
+const NOW = 1_700_000_000_000
+
+beforeEach(() => {
+ resetPairingCode()
+})
+
+afterEach(() => {
+ resetPairingCode()
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+describe('pairingCodeOf', () => {
+ it('生成 8 位大写字母数字配对码并在有效期内保持不变', () => {
+ const first = pairingCodeOf(NOW)
+ expect(first.code).toMatch(/^[2-9A-HJ-NP-Z]{8}$/u)
+ expect(first.expiresAt).toBe(NOW + PAIRING_TTL_MS)
+ expect(first.usedSeq).toBe(0)
+ expect(pairingCodeOf(NOW + PAIRING_TTL_MS - 1)).toBe(first)
+ })
+
+ it('过期即换新码,旧码立刻失效', () => {
+ const first = pairingCodeOf(NOW)
+ const next = pairingCodeOf(NOW + PAIRING_TTL_MS)
+ expect(next.code).not.toBe(first.code)
+ expect(tokenMatches(first.code.toLowerCase(), next.code)).toBe(false)
+ expect(tokenMatches(next.code.toLowerCase(), next.code)).toBe(true)
+ expect(next.expiresAt).toBe(NOW + PAIRING_TTL_MS * 2)
+ expect(next.usedSeq).toBe(0)
+ expect(pairingCodeOf(NOW + PAIRING_TTL_MS)).toBe(next)
+ })
+
+ it('新旧码不相等且不会因为重复读取而漂移', () => {
+ const codes = new Set<string>()
+ for (let index = 0; index < 32; index += 1) {
+ resetPairingCode()
+ codes.add(pairingCodeOf(NOW).code)
+ }
+ expect(codes.size).toBe(32)
+ })
+})
+
+describe('临时配对码消费', () => {
+ it('小写码只能消费一次,立即换新码且仅成功时推进 usedSeq', () => {
+ vi.spyOn(Date, 'now').mockReturnValue(NOW)
+ const first = pairingCodeOf()
+ expect(consumePairingCode('invalid')).toBe(false)
+ expect(pairingCodeOf()).toBe(first)
+ expect(consumePairingCode(first.code.toLowerCase())).toBe(true)
+ const next = pairingCodeOf()
+ expect(next.code).not.toBe(first.code)
+ expect(next.expiresAt).toBe(NOW + PAIRING_TTL_MS)
+ expect(next.usedSeq).toBe(1)
+ expect(consumePairingCode(first.code)).toBe(false)
+ expect(pairingCodeOf()).toBe(next)
+ expect(consumePairingCode(next.code)).toBe(true)
+ const afterUse = pairingCodeOf()
+ expect(afterUse.usedSeq).toBe(2)
+ const afterExpiry = pairingCodeOf(afterUse.expiresAt)
+ expect(afterExpiry.code).not.toBe(afterUse.code)
+ expect(afterExpiry.usedSeq).toBe(2)
+ })
+
+ it('到期边界拒绝旧码,不把自动轮换记成使用', () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(NOW)
+ const first = pairingCodeOf()
+ clock.mockReturnValue(NOW + PAIRING_TTL_MS)
+ expect(consumePairingCode(first.code)).toBe(false)
+ expect(pairingCodeOf().usedSeq).toBe(0)
+ })
+
+ it('通知所有等待者,并在已消费后注册时不丢事件', async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(NOW)
+ const first = pairingCodeOf()
+ const left = waitForPairingUse(0)
+ const right = waitForPairingUse(0)
+ expect(consumePairingCode(first.code.toLowerCase())).toBe(true)
+ await expect(Promise.all([left, right])).resolves.toEqual([undefined, undefined])
+ await expect(waitForPairingUse(0)).resolves.toBeUndefined()
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('等待只由消费或八秒超时结束,期限自动轮换不通知', async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(NOW)
+ const first = pairingCodeOf()
+ let settled = false
+ const pending = waitForPairingUse(0).then(() => {
+ settled = true
+ })
+ pairingCodeOf(first.expiresAt)
+ await vi.advanceTimersByTimeAsync(7999)
+ expect(settled).toBe(false)
+ await vi.advanceTimersByTimeAsync(1)
+ await pending
+ expect(settled).toBe(true)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('取消和重置移除等待者与定时器,不影响下一次等待', async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(NOW)
+ const aborted = new AbortController()
+ aborted.abort()
+ await waitForPairingUse(0, aborted.signal)
+ expect(vi.getTimerCount()).toBe(0)
+ const controller = new AbortController()
+ const cancelled = waitForPairingUse(0, controller.signal)
+ const reset = waitForPairingUse(0)
+ expect(vi.getTimerCount()).toBe(2)
+ controller.abort()
+ await cancelled
+ expect(vi.getTimerCount()).toBe(1)
+ resetPairingCode()
+ await reset
+ expect(vi.getTimerCount()).toBe(0)
+ const next = pairingCodeOf()
+ const pending = waitForPairingUse(0)
+ expect(consumePairingCode(next.code)).toBe(true)
+ await pending
+ expect(vi.getTimerCount()).toBe(0)
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/host/service/pairing.ts b/packages/dsh-tauri-remote/src/host/service/pairing.ts
new file mode 100644
index 00000000..6979b6c0
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/pairing.ts
@@ -0,0 +1,55 @@
+import { createLinkToken, tokenMatches } from '../utils/auth'
+
+export const PAIRING_TTL_MS = 5 * 60 * 1000
+
+const PAIRING_WAIT_MS = 8000
+
+const waiters = new Set<() => void>()
+
+let current: { code: string, expiresAt: number, usedSeq: number } | undefined
+
+export function pairingCodeOf(now = Date.now()): { code: string, expiresAt: number, usedSeq: number } {
+ if (current === undefined || current.expiresAt <= now) {
+ let code: string
+ do {
+ code = createLinkToken()
+ } while (code === current?.code)
+ current = { code, expiresAt: now + PAIRING_TTL_MS, usedSeq: current?.usedSeq ?? 0 }
+ }
+ return current
+}
+
+export function consumePairingCode(provided: string): boolean {
+ const now = Date.now()
+ const pairing = pairingCodeOf(now)
+ if (!tokenMatches(provided, pairing.code))
+ return false
+ current = { ...pairing, expiresAt: now, usedSeq: pairing.usedSeq + 1 }
+ pairingCodeOf(now)
+ for (const finish of waiters)
+ finish()
+ return true
+}
+
+export function waitForPairingUse(since: number, signal?: AbortSignal): Promise<void> {
+ if (pairingCodeOf().usedSeq !== since || signal?.aborted === true)
+ return Promise.resolve()
+ return new Promise((resolve) => {
+ let timer: ReturnType<typeof setTimeout>
+ const finish = (): void => {
+ clearTimeout(timer)
+ waiters.delete(finish)
+ signal?.removeEventListener('abort', finish)
+ resolve()
+ }
+ timer = setTimeout(finish, PAIRING_WAIT_MS)
+ waiters.add(finish)
+ signal?.addEventListener('abort', finish, { once: true })
+ })
+}
+
+export function resetPairingCode(): void {
+ current = undefined
+ for (const finish of waiters)
+ finish()
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/session.ts b/packages/dsh-tauri-remote/src/host/service/session.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/session.ts
rename to packages/dsh-tauri-remote/src/host/service/session.ts
diff --git a/packages/dsh-tauri-ssh/src/host/service/state.ts b/packages/dsh-tauri-remote/src/host/service/state.ts
similarity index 93%
rename from packages/dsh-tauri-ssh/src/host/service/state.ts
rename to packages/dsh-tauri-remote/src/host/service/state.ts
index feaf5c9b..12bd6457 100644
--- a/packages/dsh-tauri-ssh/src/host/service/state.ts
+++ b/packages/dsh-tauri-remote/src/host/service/state.ts
@@ -1,5 +1,5 @@
import type { MachineId, MachineProfile } from '../types/index'
-import type { SshState } from './state.types'
+import type { RemoteState } from './state.types'
import { defineService } from 'dsh-tauri'
import { machineTable } from '../config/runtime'
import { storage } from '../storage/index'
@@ -9,7 +9,7 @@ const DOCUMENT_KEY = 'state'
const STATE_VERSION = 1
export const state = defineService({
- async load(): Promise<SshState> {
+ async load(): Promise<RemoteState> {
const parsed = parseStateDocument(await storage.getItem(DOCUMENT_KEY))
machineTable.enabled = parsed.enabled
machineTable.machines = new Map(Object.entries(parsed.machines).map(([key, profile]) => [key as MachineId, profile]))
diff --git a/packages/dsh-tauri-ssh/src/host/service/state.types.ts b/packages/dsh-tauri-remote/src/host/service/state.types.ts
similarity index 79%
rename from packages/dsh-tauri-ssh/src/host/service/state.types.ts
rename to packages/dsh-tauri-remote/src/host/service/state.types.ts
index 9a36a248..4278fe41 100644
--- a/packages/dsh-tauri-ssh/src/host/service/state.types.ts
+++ b/packages/dsh-tauri-remote/src/host/service/state.types.ts
@@ -1,6 +1,6 @@
import type { MachineProfile } from '../types/index'
-export interface SshState {
+export interface RemoteState {
enabled: boolean
machines: Record<string, MachineProfile>
}
diff --git a/packages/dsh-tauri-ssh/src/host/service/state.utils.ts b/packages/dsh-tauri-remote/src/host/service/state.utils.ts
similarity index 80%
rename from packages/dsh-tauri-ssh/src/host/service/state.utils.ts
rename to packages/dsh-tauri-remote/src/host/service/state.utils.ts
index ef82565e..e92bdaaf 100644
--- a/packages/dsh-tauri-ssh/src/host/service/state.utils.ts
+++ b/packages/dsh-tauri-remote/src/host/service/state.utils.ts
@@ -1,6 +1,7 @@
import type { MachineProfile } from '../types/index'
-import type { SshState } from './state.types'
+import type { RemoteState } from './state.types'
import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
+import { DEFAULT_MACHINE_TRANSPORT } from '../config/constants'
import { MachineId as brandMachineId } from '../types/index'
export function machineProfileOf(raw: unknown): MachineProfile | undefined {
@@ -15,6 +16,10 @@ export function machineProfileOf(raw: unknown): MachineProfile | undefined {
return undefined
if (typeof value.user !== 'string')
return undefined
+ if (value.transport !== undefined && value.transport !== DEFAULT_MACHINE_TRANSPORT)
+ return undefined
+ // transport 是内存判别字段:文档里的取值只做校验,不回写 profile——否则下一次落盘
+ // 会把缺省的 ssh 固化成显式字段,违背「缺省即 ssh 不写盘」的向后兼容约定。
return {
id: brandMachineId(value.id),
name: value.name,
@@ -31,7 +36,7 @@ export function machineProfileOf(raw: unknown): MachineProfile | undefined {
}
}
-export function parseStateDocument(raw: unknown): SshState {
+export function parseStateDocument(raw: unknown): RemoteState {
if (typeof raw !== 'object' || raw === null)
return { enabled: false, machines: {} }
const record = raw as { enabled?: unknown, machines?: unknown }
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts b/packages/dsh-tauri-remote/src/host/service/sync.test.ts
similarity index 95%
rename from packages/dsh-tauri-ssh/src/host/service/sync.test.ts
rename to packages/dsh-tauri-remote/src/host/service/sync.test.ts
index 0c107c84..50f3c2d1 100644
--- a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts
+++ b/packages/dsh-tauri-remote/src/host/service/sync.test.ts
@@ -1,12 +1,12 @@
import type { Config } from '../config/schema'
-import type { SshExecResult, SshSession } from '../types/index'
+import type { RemoteExecResult, RemoteSession } from '../types/index'
import type { SyncSkillScan } from './sync.types'
import { Buffer } from 'node:buffer'
import { tmpdir } from 'node:os'
import { join } from 'pathe'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { DEFAULT_REMOTE_PROFILE } from '../config/constants'
-import { machineTable, resetRuntime, setHostConfig, setMachineDeps, setSyncDeps } from '../config/runtime'
+import { clearHostRuntime, machineTable, setHostConfig, setMachineDeps, setSyncDeps } from '../config/runtime'
import { MachineId } from '../types/index'
import { EMPTY_ALLOWLIST } from '../utils/allowlist'
import { layoutNodeBinary } from './bootstrap.utils'
@@ -14,13 +14,13 @@ import { machine } from './machine'
import { sync } from './sync'
import { buildPreview, classifySpec, installSpecOf, pluginAddCommand, skillExtractCommand } from './sync.utils'
-function fakeSession(respond: (command: string, options?: { stdinData?: Buffer }) => SshExecResult): SshSession & { execSpy: ReturnType<typeof vi.fn>, closed: () => boolean } {
+function fakeSession(respond: (command: string, options?: { stdinData?: Buffer }) => RemoteExecResult): RemoteSession & { execSpy: ReturnType<typeof vi.fn>, closed: () => boolean } {
let open = true
const execSpy = vi.fn(async (command: string, options?: { stdinData?: Buffer }) => respond(command, options))
return {
execSpy,
- exec: execSpy as unknown as SshSession['exec'],
- openTunnel: () => Promise.reject(new Error('not needed')),
+ exec: execSpy as unknown as RemoteSession['exec'],
+ stream: () => Promise.reject(new Error('not needed')),
onClosed: () => {},
close: async () => {
open = false
@@ -29,8 +29,8 @@ function fakeSession(respond: (command: string, options?: { stdinData?: Buffer }
}
}
-const ok = (stdout = ''): SshExecResult => ({ code: 0, stdout, stderr: '' })
-const fail = (stderr: string): SshExecResult => ({ code: 1, stdout: '', stderr })
+const ok = (stdout = ''): RemoteExecResult => ({ code: 0, stdout, stderr: '' })
+const fail = (stderr: string): RemoteExecResult => ({ code: 1, stdout: '', stderr })
describe('classifySpec', () => {
it('accepts remotely installable specs', () => {
@@ -133,7 +133,7 @@ describe('syncEngine.apply', () => {
const machineId = MachineId('m1')
interface Wiring {
- connect: () => Promise<SshSession>
+ connect: () => Promise<RemoteSession>
profileDependencies?: () => Record<string, string>
scanSkills?: () => SyncSkillScan[]
packSkills?: (dir: string, names: readonly string[]) => Promise<Buffer>
@@ -141,9 +141,13 @@ describe('syncEngine.apply', () => {
}
function seed(wiring: Wiring): void {
- resetRuntime()
+ clearHostRuntime()
setHostConfig(HOST_CONFIG)
- setMachineDeps({ transport: { connect: wiring.connect }, emitStatus: () => {}, localAllowlist: () => EMPTY_ALLOWLIST })
+ setMachineDeps({
+ transport: { resolve: () => ({ capabilities: { exec: true, stream: true }, connect: wiring.connect }) },
+ emitStatus: () => {},
+ localAllowlist: () => EMPTY_ALLOWLIST,
+ })
setSyncDeps({
profileDependencies: wiring.profileDependencies ?? (() => ({})),
scanSkills: wiring.scanSkills ?? (() => []),
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.ts b/packages/dsh-tauri-remote/src/host/service/sync.ts
similarity index 95%
rename from packages/dsh-tauri-ssh/src/host/service/sync.ts
rename to packages/dsh-tauri-remote/src/host/service/sync.ts
index d0572283..fcff6af1 100644
--- a/packages/dsh-tauri-ssh/src/host/service/sync.ts
+++ b/packages/dsh-tauri-remote/src/host/service/sync.ts
@@ -1,5 +1,5 @@
import type { Buffer } from 'node:buffer'
-import type { MachineId, SshSession, SyncApplyResult, SyncItemResult, SyncPluginRef, SyncPreview, SyncSkillRef, SyncSkillRoot } from '../types/index'
+import type { MachineId, RemoteSession, SyncApplyResult, SyncItemResult, SyncPluginRef, SyncPreview, SyncSkillRef, SyncSkillRoot } from '../types/index'
import type { SyncDeps } from './sync.types'
import { defineService } from 'dsh-tauri'
import { syncRuntimeDeps } from '../config/runtime'
@@ -51,7 +51,7 @@ function announceItem(machineId: MachineId, progress: SyncProgress, name: string
}
async function applyPlugins(
- session: SshSession,
+ session: RemoteSession,
deps: SyncDeps,
plugins: readonly SyncPluginRef[],
items: SyncItemResult[],
@@ -98,7 +98,7 @@ async function applyPlugins(
}
}
-async function grantBuildKeys(session: SshSession, profileName: string, output: string): Promise<string[]> {
+async function grantBuildKeys(session: RemoteSession, profileName: string, output: string): Promise<string[]> {
const keys = parseBuildAllowKeys(output)
if (keys.length === 0)
return []
@@ -109,7 +109,7 @@ async function grantBuildKeys(session: SshSession, profileName: string, output:
}
async function applySkills(
- session: SshSession,
+ session: RemoteSession,
deps: SyncDeps,
skills: readonly SyncSkillRef[],
items: SyncItemResult[],
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.types.ts b/packages/dsh-tauri-remote/src/host/service/sync.types.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/sync.types.ts
rename to packages/dsh-tauri-remote/src/host/service/sync.types.ts
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.utils.ts b/packages/dsh-tauri-remote/src/host/service/sync.utils.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/sync.utils.ts
rename to packages/dsh-tauri-remote/src/host/service/sync.utils.ts
diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.ts b/packages/dsh-tauri-remote/src/host/service/transport.ssh.ts
similarity index 79%
rename from packages/dsh-tauri-ssh/src/host/service/transport.ts
rename to packages/dsh-tauri-remote/src/host/service/transport.ssh.ts
index 77151da4..ec9f15a5 100644
--- a/packages/dsh-tauri-ssh/src/host/service/transport.ts
+++ b/packages/dsh-tauri-remote/src/host/service/transport.ssh.ts
@@ -1,30 +1,30 @@
+import type { Buffer } from 'node:buffer'
import type { AddressInfo, Server, Socket } from 'node:net'
import type { Duplex } from 'node:stream'
-import type { ConnectConfig } from 'ssh2'
-import type { MachineProfile, SshAuthMethod, SshExecOptions, SshExecResult, SshSession, SshTunnelHandle, TunnelHeaderInjection } from '../types/index'
+import type { CompressionAlgorithm, ConnectConfig } from 'ssh2'
+import type { MachineProfile, RemoteAuthMethod, RemoteExecOptions, RemoteExecResult, RemoteSession, RemoteStreamHandle } from '../types/index'
import type { ResolvedSshAuth } from '../utils/ssh-config'
-import type { SshHostKeyVerifier, SshTransportOptions } from './transport.types'
-import { Buffer } from 'node:buffer'
+import type { RemoteHostKeyVerifier, RemoteTransport, RemoteTransportOptions } from './transport.types'
import { createServer } from 'node:net'
import process from 'node:process'
-import { defineService } from 'dsh-tauri'
import { Client } from 'ssh2'
import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
import { MachineId } from '../types/index'
import { loginShell } from '../utils/shell'
-import { classifyConnectFailure, describeConnectFailure, injectCookieHead } from './transport.utils'
+import { classifyConnectFailure, describeConnectFailure } from './transport.utils'
-const TUNNEL_HEAD_CAP = 64 * 1024
+const COMPRESSION_ALGORITHMS: CompressionAlgorithm[] = ['[email protected]', 'none']
const DEFAULT_KEEPALIVE_INTERVAL_MS = 10_000
const DEFAULT_KEEPALIVE_COUNT_MAX = 3
-export const transport = defineService({
+export const sshTransport: RemoteTransport = {
+ capabilities: { exec: true, stream: true },
async connect(
profile: MachineProfile,
- hostKeyVerifier: SshHostKeyVerifier,
- options: SshTransportOptions,
+ hostKeyVerifier: RemoteHostKeyVerifier,
+ options: RemoteTransportOptions,
signal?: AbortSignal,
- ): Promise<SshSession> {
+ ): Promise<RemoteSession> {
const hops: Ssh2Session[] = []
try {
const credentials = await options.resolveProfile(profile)
@@ -41,7 +41,7 @@ export const transport = defineService({
throw error
}
},
-})
+}
// --- internal ---
@@ -71,8 +71,8 @@ function parseProxyJumpHop(token: string): ProxyJumpHop {
async function connectTarget(
credentials: ResolvedSshAuth,
label: string,
- hostKeyVerifier: SshHostKeyVerifier,
- options: SshTransportOptions,
+ hostKeyVerifier: RemoteHostKeyVerifier,
+ options: RemoteTransportOptions,
signal: AbortSignal | undefined,
hops: Ssh2Session[],
visited: ReadonlySet<string>,
@@ -116,8 +116,8 @@ async function connectTarget(
function connectWithAuth(
auth: ResolvedSshAuth,
label: string,
- hostKeyVerifier: SshHostKeyVerifier,
- options: SshTransportOptions,
+ hostKeyVerifier: RemoteHostKeyVerifier,
+ options: RemoteTransportOptions,
signal: AbortSignal | undefined,
sock: Duplex | undefined,
): Promise<Ssh2Session> {
@@ -137,7 +137,7 @@ function connectWithAuth(
signal?.removeEventListener('abort', onAbort)
fn()
}
- let winningMethod: SshAuthMethod | undefined
+ let winningMethod: RemoteAuthMethod | undefined
let passwordOffered = false
client.on('ready', () => {
settle(() => resolve(new Ssh2Session(client, winningMethod)))
@@ -183,6 +183,7 @@ function connectWithAuth(
readyTimeout: options.readyTimeoutMs,
keepaliveInterval: options.keepaliveIntervalMs ?? DEFAULT_KEEPALIVE_INTERVAL_MS,
keepaliveCountMax: options.keepaliveCountMax ?? DEFAULT_KEEPALIVE_COUNT_MAX,
+ algorithms: { compress: COMPRESSION_ALGORITHMS },
authHandler,
hostVerifier: (key: Buffer, verify: (valid: boolean) => void): void => {
const verdict = hostKeyVerifier(label, key)
@@ -206,13 +207,13 @@ function describedConnectFailure(error: Error, passwordOffered: boolean): Error
return new Error(message)
}
-class Ssh2Session implements SshSession {
+class Ssh2Session implements RemoteSession {
private readonly closed = new Set<() => void>()
private closedFired = false
constructor(
private readonly client: Client,
- readonly authMethod: SshAuthMethod | undefined = undefined,
+ readonly authMethod: RemoteAuthMethod | undefined = undefined,
) {
this.client.on('close', () => {
if (this.closedFired)
@@ -235,8 +236,8 @@ class Ssh2Session implements SshSession {
})
}
- exec(command: string, options?: SshExecOptions): Promise<SshExecResult> {
- return new Promise<SshExecResult>((resolve, reject) => {
+ exec(command: string, options?: RemoteExecOptions): Promise<RemoteExecResult> {
+ return new Promise<RemoteExecResult>((resolve, reject) => {
let settled = false
const timer = options?.timeoutMs === undefined
? undefined
@@ -294,12 +295,12 @@ class Ssh2Session implements SshSession {
})
}
- openTunnel(remotePort: number, preferredLocalPort?: number, injection?: TunnelHeaderInjection): Promise<SshTunnelHandle> {
- return this.listenTunnel(remotePort, preferredLocalPort, true, injection)
+ stream(remotePort: number, preferredLocalPort?: number): Promise<RemoteStreamHandle> {
+ return this.listenTunnel(remotePort, preferredLocalPort, true)
}
- private listenTunnel(remotePort: number, preferredLocalPort: number | undefined, allowFallback: boolean, injection?: TunnelHeaderInjection): Promise<SshTunnelHandle> {
- return new Promise<SshTunnelHandle>((resolve, reject) => {
+ private listenTunnel(remotePort: number, preferredLocalPort: number | undefined, allowFallback: boolean): Promise<RemoteStreamHandle> {
+ return new Promise<RemoteStreamHandle>((resolve, reject) => {
const sockets = new Set<Socket>()
const server: Server = createServer((socket) => {
sockets.add(socket)
@@ -314,17 +315,12 @@ class Ssh2Session implements SshSession {
return
}
channel.on('error', () => socket.destroy())
- const cookie = injection?.cookie
- if (cookie === undefined) {
- socket.pipe(channel).pipe(socket)
- return
- }
- pipeChannelWithCookie(socket, channel, cookie)
+ socket.pipe(channel).pipe(socket)
})
})
server.on('error', (error: NodeJS.ErrnoException) => {
if (allowFallback && error.code === 'EADDRINUSE' && preferredLocalPort !== undefined) {
- void this.listenTunnel(remotePort, undefined, false, injection).then(resolve, reject)
+ void this.listenTunnel(remotePort, undefined, false).then(resolve, reject)
return
}
reject(error)
@@ -356,41 +352,6 @@ class Ssh2Session implements SshSession {
}
}
-function pipeChannelWithCookie(socket: Socket, channel: Duplex, cookie: string): void {
- const buffered: Buffer[] = []
- let bufferedLength = 0
- let injected = false
- const writeToChannel = (data: Buffer): void => {
- if (!channel.write(data))
- socket.pause()
- }
- socket.on('data', (chunk: Buffer) => {
- if (injected) {
- writeToChannel(chunk)
- return
- }
- buffered.push(chunk)
- bufferedLength += chunk.length
- const whole = Buffer.concat(buffered)
- const headEnd = whole.indexOf('\r\n\r\n')
- if (headEnd === -1) {
- if (bufferedLength > TUNNEL_HEAD_CAP) {
- injected = true
- writeToChannel(whole)
- }
- return
- }
- injected = true
- const head = whole.subarray(0, headEnd).toString('latin1')
- const rest = whole.subarray(headEnd)
- writeToChannel(Buffer.concat([Buffer.from(injectCookieHead(head, cookie), 'latin1'), rest]))
- })
- socket.on('end', () => channel.end())
- channel.on('drain', () => socket.resume())
- channel.on('end', () => socket.end())
- channel.pipe(socket)
-}
-
function abortError(signal: AbortSignal): Error {
const reason: unknown = signal.reason
if (reason instanceof Error)
diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.test.ts b/packages/dsh-tauri-remote/src/host/service/transport.test.ts
similarity index 90%
rename from packages/dsh-tauri-ssh/src/host/service/transport.test.ts
rename to packages/dsh-tauri-remote/src/host/service/transport.test.ts
index e339caba..e4dc727b 100644
--- a/packages/dsh-tauri-ssh/src/host/service/transport.test.ts
+++ b/packages/dsh-tauri-remote/src/host/service/transport.test.ts
@@ -1,6 +1,6 @@
import type { AddressInfo } from 'node:net'
-import type { MachineProfile, SshSession } from '../types/index'
-import type { SshCredentialsResolver, SshHostKeyVerifier, SshTransportOptions } from './transport.types'
+import type { MachineProfile, RemoteSession } from '../types/index'
+import type { RemoteCredentialsResolver, RemoteHostKeyVerifier, RemoteTransportOptions } from './transport.types'
import { Buffer } from 'node:buffer'
import { EventEmitter } from 'node:events'
import { Server, connect as tcpConnect } from 'node:net'
@@ -9,15 +9,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { MachineId } from '../types/index'
import { loginShell, shQuote } from '../utils/shell'
import { transport } from './transport'
-import { classifyConnectFailure, describeConnectFailure, injectCookieHead } from './transport.utils'
+import { sshTransport } from './transport.ssh'
+import { classifyConnectFailure, describeConnectFailure } from './transport.utils'
const READY_TIMEOUT_MS = 15_000
-function newTransport(resolver: SshCredentialsResolver, options: Partial<SshTransportOptions> = {}) {
- const settings: SshTransportOptions = { readyTimeoutMs: READY_TIMEOUT_MS, resolveProfile: resolver, ...options }
+function newTransport(resolver: RemoteCredentialsResolver, options: Partial<RemoteTransportOptions> = {}) {
+ const settings: RemoteTransportOptions = { readyTimeoutMs: READY_TIMEOUT_MS, resolveProfile: resolver, ...options }
return {
- async connect(profile: MachineProfile, hostKeyVerifier: SshHostKeyVerifier, signal?: AbortSignal): Promise<SshSession> {
- return await transport.connect(profile, hostKeyVerifier, settings, signal)
+ async connect(profile: MachineProfile, hostKeyVerifier: RemoteHostKeyVerifier, signal?: AbortSignal): Promise<RemoteSession> {
+ return await transport.resolve(profile).connect(profile, hostKeyVerifier, settings, signal)
},
}
}
@@ -44,7 +45,7 @@ function stubResolver(plan: {
port?: number
username?: string
keys?: Array<{ privateKey: string, passphrase?: string }>
-} = {}): SshCredentialsResolver {
+} = {}): RemoteCredentialsResolver {
return async (input: MachineProfile) => {
const password = input.password === undefined || input.password === '' ? undefined : input.password
return {
@@ -366,6 +367,13 @@ describe('ssh2Transport', () => {
await session.close()
})
+ it('offers [email protected] ahead of none for link compression', async () => {
+ const transport = newTransport(stubResolver())
+ const session = await transport.connect(profile, () => true)
+ expect(lastClient().connectConfig?.algorithms).toEqual({ compress: ['[email protected]', 'none'] })
+ await session.close()
+ })
+
it('reports the winning auth method on the session', async () => {
process.env.SSH_AUTH_SOCK = '/tmp/agent.sock'
const resolver = stubResolver({ keys: [{ privateKey: 'KEY-A' }] })
@@ -386,7 +394,7 @@ describe('ssh2Transport', () => {
})
it('rejects when the resolver fails', async () => {
- const failing: SshCredentialsResolver = async () => {
+ const failing: RemoteCredentialsResolver = async () => {
throw new Error('config read failed')
}
const transport = newTransport(failing)
@@ -523,7 +531,7 @@ describe('ssh2Transport', () => {
it('forwards the remote port to a loopback listener', async () => {
const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
- const tunnel = await session.openTunnel(3080)
+ const tunnel = await session.stream(3080)
expect(tunnel.localPort).toBeGreaterThan(0)
await tunnel.close()
await session.close()
@@ -532,7 +540,7 @@ describe('ssh2Transport', () => {
it('pipes real socket traffic through the tunnel', async () => {
const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
- const tunnel = await session.openTunnel(3080)
+ const tunnel = await session.stream(3080)
const socket = tcpConnect(tunnel.localPort, '127.0.0.1')
await new Promise<void>(resolve => socket.once('connect', () => resolve()))
socket.write('ping')
@@ -546,7 +554,7 @@ describe('ssh2Transport', () => {
it('destroys open sockets when the tunnel closes', async () => {
const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
- const tunnel = await session.openTunnel(3080)
+ const tunnel = await session.stream(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))
@@ -558,7 +566,7 @@ describe('ssh2Transport', () => {
it('destroys the client socket when the tunnel channel fails', async () => {
const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
- const tunnel = await session.openTunnel(3080)
+ const tunnel = await session.stream(3080)
lastClient().forwardError = new Error('tunnel closed')
const socket = tcpConnect(tunnel.localPort, '127.0.0.1')
await new Promise<void>((resolve, reject) => {
@@ -576,7 +584,7 @@ describe('ssh2Transport', () => {
// 只销毁对应连接;若仍有未处理错误,vitest worker 会直接崩溃。
const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
- const tunnel = await session.openTunnel(3080)
+ const tunnel = await session.stream(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))
@@ -595,7 +603,7 @@ describe('ssh2Transport', () => {
})
const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
- await expect(session.openTunnel(3080)).rejects.toThrow('EADDRINUSE')
+ await expect(session.stream(3080)).rejects.toThrow('EADDRINUSE')
await session.close()
})
@@ -628,7 +636,7 @@ describe('ssh2Transport', () => {
await new Promise<void>(resolve => holder.close(() => resolve()))
const transport = newTransport(stubResolver(), keepalive)
const session = await transport.connect(profile, () => true)
- const tunnel = await session.openTunnel(3080, freePort)
+ const tunnel = await session.stream(3080, freePort)
expect(tunnel.localPort).toBe(freePort)
await tunnel.close()
await session.close()
@@ -641,7 +649,7 @@ describe('ssh2Transport', () => {
const takenPort = (holder.address() as AddressInfo).port
const transport = newTransport(stubResolver(), keepalive)
const session = await transport.connect(profile, () => true)
- const tunnel = await session.openTunnel(3080, takenPort)
+ const tunnel = await session.stream(3080, takenPort)
expect(tunnel.localPort).not.toBe(takenPort)
expect(tunnel.localPort).toBeGreaterThan(0)
await tunnel.close()
@@ -718,7 +726,7 @@ function jumpResolver(plans: Record<string, {
port: number
username?: string
proxyJump?: string[]
-}>): SshCredentialsResolver {
+}>): RemoteCredentialsResolver {
return async (input: MachineProfile) => {
const plan = plans[input.host]
if (plan === undefined)
@@ -823,62 +831,36 @@ describe('ssh2Transport ProxyJump', () => {
})
})
-describe('injectCookieHead', () => {
- it('replaces Cookie, forces Connection: close, keeps the request line first', () => {
- const head = 'GET / HTTP/1.1\r\nHost: 127.0.0.1:5000\r\nConnection: keep-alive\r\nCookie: stale=1'
- const out = injectCookieHead(head, 'dsh-auth-x=v1.signed')
- const lines = out.split('\r\n')
- expect(lines[0]).toBe('GET / HTTP/1.1')
- expect(lines).toContain('Cookie: dsh-auth-x=v1.signed')
- expect(lines).toContain('Connection: close')
- expect(lines.some(line => /keep-alive/iu.test(line))).toBe(false)
- expect(lines.filter(line => /^cookie:/iu.test(line))).toHaveLength(1)
- })
-
- it('keeps Connection: Upgrade untouched for websocket handshakes', () => {
- const head = 'GET /ws HTTP/1.1\r\nHost: x\r\nConnection: Upgrade\r\nUpgrade: websocket'
- const out = injectCookieHead(head, 'dsh-auth-x=v1.signed')
- expect(out).toContain('Connection: Upgrade')
- expect(out).not.toContain('Connection: close')
- expect(out).toContain('Cookie: dsh-auth-x=v1.signed')
- })
-})
-
-describe('tunnel cookie injection', () => {
- it('stamps the request head with the minted cookie through the pipe', async () => {
+describe('tunnel transparency', () => {
+ it('relays the request head byte-for-byte without injecting a cookie', async () => {
const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
- const injection = { cookie: 'dsh-auth-x=v1.signed' as string | undefined }
- const tunnel = await session.openTunnel(3080, undefined, injection)
+ const tunnel = await session.stream(3080)
const socket = tcpConnect(tunnel.localPort, '127.0.0.1')
await new Promise<void>(resolve => socket.once('connect', () => resolve()))
- // PassThrough 回环:写入 channel 的字节流(= 注入后的请求)回到 socket
+ // PassThrough 回环:写入 channel 的字节流回到 socket,可逐字节比对
const echoed: Buffer[] = []
socket.on('data', chunk => echoed.push(chunk as Buffer))
- socket.write('GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n')
+ const head = 'GET / HTTP/1.1\r\nHost: 127.0.0.1:3080\r\nConnection: keep-alive\r\nCookie: viewer=1\r\n\r\n'
+ socket.write(head)
await new Promise(resolve => setTimeout(resolve, 30))
- const received = Buffer.concat(echoed).toString('latin1')
- expect(received).toContain('Cookie: dsh-auth-x=v1.signed')
- expect(received).toContain('Connection: close')
- expect(received.startsWith('GET / HTTP/1.1')).toBe(true)
+ expect(Buffer.concat(echoed).toString('latin1')).toBe(head)
socket.destroy()
await tunnel.close()
await session.close()
})
+})
- it('without a minted cookie the tunnel stays a plain pipe', async () => {
- const transport = newTransport(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()))
- const echoed: Buffer[] = []
- socket.on('data', chunk => echoed.push(chunk as Buffer))
- socket.write('ping')
- await new Promise(resolve => setTimeout(resolve, 30))
- expect(Buffer.concat(echoed).toString('latin1')).toBe('ping')
- socket.destroy()
- await tunnel.close()
- await session.close()
+describe('transport registry', () => {
+ it('resolves the ssh implementation for a profile without a transport field', () => {
+ expect(transport.resolve(profile)).toBe(sshTransport)
+ })
+
+ it('resolves the ssh implementation for an explicit ssh transport', () => {
+ expect(transport.resolve({ ...profile, transport: 'ssh' })).toBe(sshTransport)
+ })
+
+ it('declares exec and stream capabilities for the ssh transport', () => {
+ expect(transport.resolve(profile).capabilities).toEqual({ exec: true, stream: true })
})
})
diff --git a/packages/dsh-tauri-remote/src/host/service/transport.ts b/packages/dsh-tauri-remote/src/host/service/transport.ts
new file mode 100644
index 00000000..ac3420a3
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/transport.ts
@@ -0,0 +1,13 @@
+import type { MachineProfile, MachineTransport } from '../types/index'
+import type { RemoteTransport } from './transport.types'
+import { defineService } from 'dsh-tauri'
+import { DEFAULT_MACHINE_TRANSPORT } from '../config/constants'
+import { sshTransport } from './transport.ssh'
+
+const IMPLEMENTATIONS: Readonly<Record<MachineTransport, RemoteTransport>> = { ssh: sshTransport }
+
+export const transport = defineService({
+ resolve(profile: MachineProfile): RemoteTransport {
+ return IMPLEMENTATIONS[profile.transport ?? DEFAULT_MACHINE_TRANSPORT]
+ },
+})
diff --git a/packages/dsh-tauri-remote/src/host/service/transport.types.ts b/packages/dsh-tauri-remote/src/host/service/transport.types.ts
new file mode 100644
index 00000000..1d7fd51e
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/transport.types.ts
@@ -0,0 +1,41 @@
+import type { Buffer } from 'node:buffer'
+import type { MachineProfile, RemoteSession } from '../types/index'
+import type { ResolvedSshAuth } from '../utils/ssh-config'
+
+export type RemoteCredentialsResolver = (profile: MachineProfile) => Promise<ResolvedSshAuth>
+
+export interface RemoteTransportOptions {
+ readyTimeoutMs: number
+ resolveProfile: RemoteCredentialsResolver
+ keepaliveIntervalMs?: number
+ keepaliveCountMax?: number
+}
+
+export type RemoteHostKeyVerifier = (label: string, hostKey: Buffer) => boolean | Promise<boolean>
+
+/** transport 的能力声明:状态机据此分支,不按实现名分支。 */
+export interface RemoteTransportCapabilities {
+ exec: boolean
+ stream: boolean
+}
+
+export interface RemoteTransport {
+ capabilities: RemoteTransportCapabilities
+ connect: (
+ profile: MachineProfile,
+ hostKeyVerifier: RemoteHostKeyVerifier,
+ options: RemoteTransportOptions,
+ signal?: AbortSignal,
+ ) => Promise<RemoteSession>
+}
+
+/** 按档案的 `transport` 判别字段选出实现的注册表;状态机只依赖本接口。 */
+export interface RemoteTransportResolver {
+ resolve: (profile: MachineProfile) => RemoteTransport
+}
+
+export type RemoteConnectFailureKind
+ = | 'key-rejected'
+ | 'password-rejected'
+ | 'unreachable'
+ | 'other'
diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.utils.ts b/packages/dsh-tauri-remote/src/host/service/transport.utils.ts
similarity index 54%
rename from packages/dsh-tauri-ssh/src/host/service/transport.utils.ts
rename to packages/dsh-tauri-remote/src/host/service/transport.utils.ts
index bcb46cc6..b693b682 100644
--- a/packages/dsh-tauri-ssh/src/host/service/transport.utils.ts
+++ b/packages/dsh-tauri-remote/src/host/service/transport.utils.ts
@@ -1,5 +1,4 @@
-import type { SshConnectFailureKind } from './transport.types'
-import { get as httpGet } from 'node:http'
+import type { RemoteConnectFailureKind } from './transport.types'
const UNREACHABLE_CODES = new Set([
'ENOTFOUND',
@@ -18,7 +17,7 @@ function isUnreachable(error: Error): boolean {
return /timed?\s?out|connection refused|econnrefused|no route to host|name or service not known|getaddrinfo/iu.test(error.message)
}
-export function classifyConnectFailure(error: unknown, passwordOffered: boolean): SshConnectFailureKind {
+export function classifyConnectFailure(error: unknown, passwordOffered: boolean): RemoteConnectFailureKind {
const message = error instanceof Error ? error.message : String(error)
const normalized = error instanceof Error ? error : new Error(message)
if (isUnreachable(normalized))
@@ -28,7 +27,7 @@ export function classifyConnectFailure(error: unknown, passwordOffered: boolean)
return 'other'
}
-export function describeConnectFailure(kind: SshConnectFailureKind, error: unknown): string {
+export function describeConnectFailure(kind: RemoteConnectFailureKind, error: unknown): string {
const message = error instanceof Error ? error.message : String(error)
switch (kind) {
case 'key-rejected':
@@ -41,30 +40,3 @@ export function describeConnectFailure(kind: SshConnectFailureKind, error: unkno
return message === '' ? 'SSH connection failed' : message
}
}
-
-export function injectCookieHead(head: string, cookie: string): string {
- const lines = head.split('\r\n')
- const isUpgrade = lines.some(line => /^connection:\s*upgrade/iu.test(line))
- const kept = lines.filter(line =>
- !/^cookie:/iu.test(line) && (isUpgrade || !/^connection:/iu.test(line)))
- kept.splice(1, 0, `Cookie: ${cookie}`)
- if (!isUpgrade)
- kept.splice(2, 0, 'Connection: close')
- return kept.join('\r\n')
-}
-
-export function mintTunnelCookie(authenticatedUrl: string): Promise<string | undefined> {
- return new Promise((resolve) => {
- const request = httpGet(authenticatedUrl, (response) => {
- response.resume()
- const raw = response.headers['set-cookie']?.[0]
- const pair = raw === undefined ? undefined : raw.split(';')[0]?.trim()
- resolve(pair === undefined || pair === '' ? undefined : pair)
- })
- request.on('error', () => resolve(undefined))
- request.setTimeout(3_000, () => {
- request.destroy()
- resolve(undefined)
- })
- })
-}
diff --git a/packages/dsh-tauri-remote/src/host/service/tunnel.test.ts b/packages/dsh-tauri-remote/src/host/service/tunnel.test.ts
new file mode 100644
index 00000000..70f0e05b
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/tunnel.test.ts
@@ -0,0 +1,226 @@
+import type { RemoteAuthPolicy, RemoteHostContext } from '../types/index'
+import type { TunnelHandlers, TunnelProcess } from './tunnel.types'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'pathe'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { setCurrentHostInstance, setTunnelDeps } from '../config/runtime'
+import { defaultAccessDocument, readAccessDocument, writeAccessDocument } from './access.utils'
+import { gateway } from './gateway'
+import { tunnel } from './tunnel'
+
+const HOST_PORT = 45_678
+
+const POLICY: RemoteAuthPolicy = { enabled: true, scope: 'public_only', password: null, linkToken: 'link-token', sessionSecret: 'session-secret' }
+
+interface Spawned {
+ env?: NodeJS.ProcessEnv
+ binary: string
+ args: string[]
+ handlers: TunnelHandlers
+ kills: NodeJS.Signals[]
+ crash: (code: number | null) => void
+}
+
+const homes: string[] = []
+
+let previousHome: string | undefined
+
+let previousPort: string | undefined
+
+let spawned: Spawned[] = []
+
+function hostContext(): RemoteHostContext {
+ return {
+ webServer: { register: () => () => {}, port: HOST_PORT },
+ effect: () => {},
+ connection: { authenticatedUrl: (base: string) => `${base}?token=launch-token` },
+ } as unknown as RemoteHostContext
+}
+
+function stubSpawn(binary: string, args: string[], handlers: TunnelHandlers, env?: NodeJS.ProcessEnv): TunnelProcess {
+ let settle: () => void = () => {}
+ const record: Spawned = {
+ binary,
+ args,
+ env,
+ handlers,
+ kills: [],
+ crash: (code) => {
+ handlers.onExit(code, null)
+ settle()
+ },
+ }
+ spawned.push(record)
+ return {
+ pid: 4242,
+ exited: new Promise<void>((resolve) => {
+ settle = resolve
+ }),
+ kill: (signal) => {
+ record.kills.push(signal)
+ handlers.onExit(null, signal)
+ settle()
+ },
+ }
+}
+
+beforeEach(() => {
+ previousHome = process.env.DSH_HOME
+ previousPort = process.env.DSH_WEB_PORT
+ process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'dsh-remote-tunnel-'))
+ homes.push(process.env.DSH_HOME)
+ spawned = []
+ setCurrentHostInstance(hostContext())
+ setTunnelDeps({
+ policy: () => POLICY,
+ resolveBinary: async () => '/stub/cloudflared',
+ spawn: stubSpawn,
+ })
+})
+
+afterEach(async () => {
+ await tunnel.dispose()
+ await gateway.dispose()
+ setCurrentHostInstance(undefined)
+ if (previousHome === undefined)
+ delete process.env.DSH_HOME
+ else
+ process.env.DSH_HOME = previousHome
+ if (previousPort === undefined)
+ delete process.env.DSH_WEB_PORT
+ else
+ process.env.DSH_WEB_PORT = previousPort
+ for (const home of homes.splice(0))
+ rmSync(home, { recursive: true, force: true })
+})
+
+describe('tunnel 生命周期', () => {
+ it('quick 模式:入口按 tunnel 类型监听回环,解析到 trycloudflare 域名后进入 running 并落盘 hostname', async () => {
+ await tunnel.start('quick')
+ const entry = gateway.status('tunnel')
+ expect(entry?.kind).toBe('tunnel')
+ expect(entry?.host).toBe('127.0.0.1')
+ expect(entry?.upstream).toBe(`http://127.0.0.1:${HOST_PORT}`)
+ expect(spawned).toHaveLength(1)
+ expect(spawned[0]?.binary).toBe('/stub/cloudflared')
+ expect(spawned[0]?.args).toEqual(['tunnel', '--no-autoupdate', '--url', `http://127.0.0.1:${entry?.port}`])
+
+ const starting = await tunnel.status()
+ expect(starting.state).toBe('starting')
+ expect(starting.mode).toBe('quick')
+ expect(starting.port).toBe(entry?.port)
+ expect(starting.url).toBeUndefined()
+
+ spawned[0]?.handlers.onLine('2026-10-06T00:00:00Z INF Your quick Tunnel has been created! Visit it at https://bold-fox-abc.trycloudflare.com')
+ const running = await tunnel.status()
+ expect(running.state).toBe('running')
+ expect(running.url).toBe('https://bold-fox-abc.trycloudflare.com')
+ expect(running.hostname).toBe('bold-fox-abc.trycloudflare.com')
+ expect(readAccessDocument().document.tunnel).toEqual({ enabled: true, mode: 'quick', token: null, hostname: 'bold-fox-abc.trycloudflare.com' })
+ expect(running.events.some(event => event.kind === 'process' && event.line.includes('trycloudflare'))).toBe(true)
+ })
+
+ it('token 模式:用具名凭据启动并以配置的公开主机名作为链接', async () => {
+ await tunnel.start('token', 'cf-token', 'dsh.example.com')
+ expect(spawned[0]?.args).toEqual(['tunnel', '--no-autoupdate', 'run'])
+ expect(spawned[0]?.args.join(' '), '凭据不得出现在进程参数里').not.toContain('cf-token')
+ expect(spawned[0]?.env).toEqual({ TUNNEL_TOKEN: 'cf-token' })
+ const status = await tunnel.status()
+ expect(status.state).toBe('running')
+ expect(status.url).toBe('https://dsh.example.com')
+ expect(status.token).toBe('cf-token')
+ expect(readAccessDocument().document.tunnel).toEqual({ enabled: true, mode: 'token', token: 'cf-token', hostname: 'dsh.example.com' })
+ })
+
+ it('并发 start/stop 串行化:最终只留一次启动,进程被回收', async () => {
+ const starting = tunnel.start('quick')
+ const stopping = tunnel.stop()
+ await Promise.all([starting, stopping])
+ expect(spawned).toHaveLength(1)
+ expect(spawned[0]?.kills).toContain('SIGTERM')
+ const status = await tunnel.status()
+ expect(status.state).toBe('stopped')
+ expect(status.enabled).toBe(false)
+ })
+
+ it('access.json 损坏时拿到域名不抛错:落为可读失败而不是未捕获异常', async () => {
+ await tunnel.start('quick')
+ writeAccessDocument({ ...defaultAccessDocument(), tunnel: { enabled: true, mode: 'quick', token: null, hostname: null } })
+ // 直接把档案写坏,模拟 cloudflared 输出域名时磁盘上的配置已不可解析
+ writeFileSync(join(process.env.DSH_HOME ?? '', 'remote', 'access.json'), '{ not json')
+ expect(() => {
+ spawned[0]?.handlers.onLine('INF Your quick Tunnel has been created! Visit it at https://bold-fox-abc.trycloudflare.com')
+ }).not.toThrow()
+ await vi.waitFor(async () => {
+ expect((await tunnel.status()).state).toBe('error')
+ })
+ expect((await tunnel.status()).error).toContain('落盘')
+ })
+
+ it('token 模式缺凭据或主机名时拒绝启动,且不落盘、不装入口、不起进程', async () => {
+ await expect(tunnel.start('token')).rejects.toThrowError('Tunnel Token')
+ await expect(tunnel.start('token', 'cf-token')).rejects.toThrowError('公开主机名')
+ expect(spawned).toHaveLength(0)
+ expect(gateway.status('tunnel')).toBeUndefined()
+ expect(readAccessDocument().document.tunnel.enabled).toBe(false)
+ })
+
+ it('stop:回收进程与入口,配置保留但 enabled 落为 false', async () => {
+ await tunnel.start('quick')
+ await tunnel.stop()
+ expect(spawned[0]?.kills).toEqual(['SIGTERM'])
+ expect(gateway.status('tunnel')?.state).toBe('stopped')
+ expect(gateway.status('tunnel')?.port).toBe(0)
+ const status = await tunnel.status()
+ expect(status.state).toBe('stopped')
+ expect(status.url).toBeUndefined()
+ expect(status.port).toBeUndefined()
+ expect(readAccessDocument().document.tunnel).toEqual({ enabled: false, mode: 'quick', token: null, hostname: null })
+ })
+
+ it('cloudflared 异常退出:进入 error、入口回收、原因可读(不自动重启)', async () => {
+ await tunnel.start('quick')
+ spawned[0]?.crash(1)
+ const status = await tunnel.status()
+ expect(status.state).toBe('error')
+ expect(status.error).toContain('cloudflared 已退出')
+ await vi.waitFor(() => {
+ expect(gateway.status('tunnel')?.state).toBe('stopped')
+ })
+ expect(spawned).toHaveLength(1)
+ expect(readAccessDocument().document.tunnel.enabled).toBe(true)
+ })
+
+ it('restore:按落盘的 enabled 配置自动启动', async () => {
+ writeAccessDocument({ ...defaultAccessDocument(), tunnel: { enabled: true, mode: 'quick', token: null, hostname: null } })
+ await tunnel.restore()
+ expect((await tunnel.status()).state).toBe('starting')
+ expect(spawned).toHaveLength(1)
+ })
+
+ it('access.json 损坏时拒绝写入隧道配置,避免覆盖待修复的文件', async () => {
+ const file = join(process.env.DSH_HOME ?? '', 'remote', 'access.json')
+ mkdirSync(join(process.env.DSH_HOME ?? '', 'remote'), { recursive: true })
+ writeFileSync(file, '{ broken')
+ await expect(tunnel.start('quick')).rejects.toThrowError('access.json 解析失败')
+ expect(spawned).toHaveLength(0)
+ })
+
+ it('上游端口取宿主 webserver 的实监听端口,而不是进程环境变量', async () => {
+ process.env.DSH_WEB_PORT = '1'
+ await tunnel.start('quick')
+ expect(gateway.status('tunnel')?.upstream).toBe(`http://127.0.0.1:${HOST_PORT}`)
+ })
+
+ it('缺少可用本机端口时不装入口,并给出可读原因', async () => {
+ setCurrentHostInstance({ webServer: { register: () => () => {} }, effect: () => {} } as unknown as RemoteHostContext)
+ delete process.env.DSH_WEB_PORT
+ await tunnel.start('quick')
+ const status = await tunnel.status()
+ expect(status.state).toBe('error')
+ expect(status.error).toContain('无法确定本机 DSH 端口')
+ expect(gateway.status('tunnel')).toBeUndefined()
+ expect(spawned).toHaveLength(0)
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/host/service/tunnel.ts b/packages/dsh-tauri-remote/src/host/service/tunnel.ts
new file mode 100644
index 00000000..875b6ef1
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/tunnel.ts
@@ -0,0 +1,351 @@
+import type { RemoteTunnelConfig, RemoteTunnelEvent, RemoteTunnelMode, RemoteTunnelProgress, RemoteTunnelState, RemoteTunnelStatus } from '../types/index'
+import type { TunnelProcess } from './tunnel.types'
+import { defineService } from 'dsh-tauri'
+import { messageOf } from '../../shared/error'
+import { localUpstream, mintAuthenticatedUrl, tunnelRuntimeDeps } from '../config/runtime'
+import { parseQuickTunnelUrl, quickTunnelArgs, tokenTunnelArgs, tokenTunnelEnv } from '../utils/cloudflared'
+import { readAccessDocument, writeAccessDocument } from './access.utils'
+import { gateway } from './gateway'
+
+const ENTRY_ID = 'tunnel'
+
+const ENTRY_PORT = 3089
+
+const ENTRY_HOST = '127.0.0.1'
+
+const EVENT_CAPACITY = 50
+
+const LINE_LIMIT = 500
+
+const STOP_GRACE_MS = 5_000
+
+const PROGRESS_STEP_PERCENT = 5
+
+const PROGRESS_MIN_INTERVAL_MS = 400
+
+const NO_LOCAL_UPSTREAM = '无法确定本机 DSH 端口(宿主 webserver 未暴露端口且进程缺少 DSH_WEB_PORT),未启动隧道'
+
+const TOKEN_REQUIRED = '具名隧道需要 Tunnel Token(Cloudflare 控制台 → 隧道 → 安装连接器)'
+
+const HOSTNAME_REQUIRED = '具名隧道需要公开主机名,用于拼链接与二维码'
+
+let child: TunnelProcess | undefined
+
+let state: RemoteTunnelState = 'stopped'
+
+let url: string | undefined
+
+let failure: string | undefined
+
+let bound = 0
+
+let stopping = false
+
+let activation = 0
+
+let queue: Promise<unknown> = Promise.resolve()
+
+let sequence = 0
+
+let events: RemoteTunnelEvent[] = []
+
+let progress: RemoteTunnelProgress | undefined
+
+let lastProgressAt = 0
+
+let lastProgressPercent = -1
+
+export const tunnel = defineService({
+ async status(): Promise<RemoteTunnelStatus> {
+ const config = tunnelConfig()
+ return {
+ enabled: config.enabled,
+ mode: config.mode,
+ hostname: config.hostname,
+ ...config.token === null ? {} : { token: config.token },
+ state,
+ events: [...events],
+ ...url === undefined ? {} : { url },
+ ...bound === 0 ? {} : { port: bound },
+ ...progress === undefined ? {} : { progress },
+ ...failure === undefined ? {} : { error: failure },
+ }
+ },
+
+ /** 纯校验:不合法的入参在改动认证状态之前就抛错,避免「启动失败却已经生成密码」。 */
+ assertStartable(mode: RemoteTunnelMode, token?: string, hostname?: string): void {
+ tunnelConfigOf(mode, token, hostname)
+ },
+
+ async start(mode: RemoteTunnelMode, token?: string, hostname?: string): Promise<void> {
+ await enqueue(async () => {
+ persist(tunnelConfigOf(mode, token, hostname))
+ await activate()
+ })
+ },
+
+ async stop(): Promise<void> {
+ await enqueue(async () => {
+ persist({ ...tunnelConfig(), enabled: false })
+ await deactivate('公网隧道已停止')
+ })
+ },
+
+ async restore(): Promise<void> {
+ await enqueue(async () => {
+ const parsed = readAccessDocument()
+ for (const warning of parsed.warnings)
+ note('state', warning)
+ if (!parsed.document.tunnel.enabled)
+ return
+ await activate()
+ })
+ },
+
+ async dispose(): Promise<void> {
+ await enqueue(async () => {
+ await deactivate(undefined)
+ state = 'stopped'
+ failure = undefined
+ url = undefined
+ events = []
+ })
+ },
+})
+
+// --- internal ---
+/** 启停串行化:并发 start/stop 会各起一个 cloudflared,这里保证同一时刻只有一次状态迁移。 */
+function enqueue<T>(run: () => Promise<T>): Promise<T> {
+ const next = queue.then(run, run)
+ queue = next.then(() => undefined, () => undefined)
+ return next
+}
+
+/** 进度写入:事件环按「每 5% 或 400ms」节流,避免下载把 50 条环形缓冲刷满。 */
+function setProgress(next: RemoteTunnelProgress): void {
+ progress = next
+ if (next.stage !== 'download') {
+ note('progress', progressLine(next))
+ lastProgressAt = Date.now()
+ lastProgressPercent = -1
+ return
+ }
+ const now = Date.now()
+ const percent = next.total === undefined || next.total <= 0 ? -1 : Math.floor((next.received ?? 0) * 100 / next.total)
+ const advanced = percent < 0 ? lastProgressPercent < 0 : percent >= lastProgressPercent + PROGRESS_STEP_PERCENT
+ if (!advanced || now - lastProgressAt < PROGRESS_MIN_INTERVAL_MS)
+ return
+ lastProgressAt = now
+ lastProgressPercent = percent
+ note('progress', progressLine(next))
+}
+
+function progressLine(entry: RemoteTunnelProgress): string {
+ if (entry.stage === 'check')
+ return '检查 cloudflared 可执行文件'
+ if (entry.stage === 'download') {
+ const source = entry.url === undefined ? '' : `(${entry.url})`
+ const amount = entry.total === undefined || entry.total <= 0
+ ? `${formatBytes(entry.received ?? 0)}`
+ : `${Math.floor((entry.received ?? 0) * 100 / entry.total)}% ${formatBytes(entry.received ?? 0)}/${formatBytes(entry.total)}`
+ return `下载 cloudflared ${amount}${source}`
+ }
+ if (entry.stage === 'extract')
+ return '解压 cloudflared 安装包'
+ if (entry.stage === 'verify')
+ return '校验 cloudflared 可执行文件'
+ if (entry.stage === 'spawn')
+ return '启动 cloudflared 进程'
+ if (entry.stage === 'domain')
+ return '等待分配 trycloudflare 域名'
+ return '隧道已就绪'
+}
+
+function formatBytes(value: number): string {
+ if (value < 1024)
+ return `${value} B`
+ if (value < 1024 * 1024)
+ return `${(value / 1024).toFixed(1)} KiB`
+ return `${(value / 1024 / 1024).toFixed(1)} MiB`
+}
+
+function publicHostOf(value: string | undefined): string | undefined {
+ if (value === undefined || value === '')
+ return undefined
+ try {
+ return new URL(value).host
+ }
+ catch {
+ return undefined
+ }
+}
+function tunnelConfig(): RemoteTunnelConfig {
+ return readAccessDocument().document.tunnel
+}
+
+function tunnelConfigOf(mode: RemoteTunnelMode, token: string | undefined, hostname: string | undefined): RemoteTunnelConfig {
+ if (mode === 'token') {
+ const credential = token?.trim() ?? ''
+ const host = hostname?.trim() ?? ''
+ if (credential === '')
+ throw new Error(TOKEN_REQUIRED)
+ if (host === '')
+ throw new Error(HOSTNAME_REQUIRED)
+ return { enabled: true, mode, token: credential, hostname: host }
+ }
+ return { enabled: true, mode: 'quick', token: null, hostname: null }
+}
+
+function persist(config: RemoteTunnelConfig): void {
+ const parsed = readAccessDocument()
+ if (parsed.corrupt)
+ throw new Error('access.json 解析失败,已按未配置处理(请手工修复后再启用隧道)')
+ writeAccessDocument({ ...parsed.document, tunnel: config })
+}
+
+async function activate(): Promise<void> {
+ await deactivate(undefined)
+ const config = tunnelConfig()
+ const upstream = localUpstream()
+ if (upstream === undefined) {
+ await fail(NO_LOCAL_UPSTREAM)
+ return
+ }
+ state = 'starting'
+ failure = undefined
+ url = undefined
+ setProgress({ stage: 'check' })
+ try {
+ const binary = await tunnelRuntimeDeps().resolveBinary(setProgress)
+ const entry = await gateway.start({
+ id: ENTRY_ID,
+ kind: 'tunnel',
+ upstream,
+ port: ENTRY_PORT,
+ host: ENTRY_HOST,
+ tokenProvider: mintAuthenticatedUrl,
+ auth: () => tunnelRuntimeDeps().policy(),
+ publicHost: () => publicHostOf(url),
+ })
+ bound = entry.port
+ setProgress({ stage: 'spawn' })
+ const args = config.mode === 'token' ? tokenTunnelArgs() : quickTunnelArgs(`http://${ENTRY_HOST}:${entry.port}`)
+ const env = config.mode === 'token' ? tokenTunnelEnv(config.token ?? '') : undefined
+ const generation = ++activation
+ child = tunnelRuntimeDeps().spawn(binary, args, {
+ onLine: line => onLine(config.mode, line, generation),
+ onExit: (code, signal) => onExit(code, signal, generation),
+ }, env)
+ if (generation !== activation) {
+ // 本次激活已被并发 stop 取代:立刻回收刚起的进程,避免留下孤儿 cloudflared
+ child.kill('SIGTERM')
+ child = undefined
+ return
+ }
+ note('state', `隧道入口已监听 ${ENTRY_HOST}:${entry.port}`)
+ if (config.mode === 'token') {
+ await ready(`https://${config.hostname ?? ''}`)
+ }
+ else {
+ setProgress({ stage: 'domain' })
+ note('process', 'cloudflared 已启动,等待分配 trycloudflare 域名')
+ }
+ }
+ catch (error) {
+ await fail(messageOf(error))
+ }
+}
+
+async function deactivate(reason: string | undefined): Promise<void> {
+ activation += 1
+ progress = undefined
+ lastProgressPercent = -1
+ const running = child
+ child = undefined
+ if (running !== undefined) {
+ stopping = true
+ running.kill('SIGTERM')
+ const force = setTimeout(() => running.kill('SIGKILL'), STOP_GRACE_MS)
+ try {
+ await running.exited
+ }
+ finally {
+ clearTimeout(force)
+ stopping = false
+ }
+ }
+ await gateway.stop(ENTRY_ID)
+ bound = 0
+ url = undefined
+ if (state !== 'error' || reason !== undefined)
+ state = 'stopped'
+ if (reason !== undefined) {
+ failure = undefined
+ note('state', reason)
+ }
+}
+
+async function fail(reason: string): Promise<void> {
+ failure = reason
+ state = 'error'
+ note('state', `隧道未启动:${reason}`)
+ await deactivate(undefined)
+}
+
+async function ready(next: string): Promise<void> {
+ setProgress({ stage: 'ready' })
+ state = 'running'
+ url = next
+ note('state', `公网隧道已就绪:${next}`)
+}
+
+function onLine(mode: RemoteTunnelMode, line: string, generation: number): void {
+ if (generation !== activation)
+ return
+ const trimmed = line.trim()
+ if (trimmed === '')
+ return
+ note('process', trimmed.slice(0, LINE_LIMIT))
+ if (mode !== 'quick' || state === 'running')
+ return
+ const found = parseQuickTunnelUrl(trimmed)
+ if (found === undefined)
+ return
+ try {
+ persist({ ...tunnelConfig(), hostname: hostOf(found) })
+ }
+ catch (error) {
+ // access.json 损坏时写入会抛错:这里必须自己兜住,否则异常从子进程日志回调里冒出去。
+ void fail(`已拿到隧道域名但无法落盘:${messageOf(error)}`)
+ return
+ }
+ void ready(found)
+}
+
+function onExit(code: number | null, signal: NodeJS.Signals | null, generation: number): void {
+ if (generation !== activation)
+ return
+ child = undefined
+ bound = 0
+ if (stopping)
+ return
+ state = 'error'
+ url = undefined
+ failure = `cloudflared 已退出(${signal ?? code ?? '未知原因'})`
+ note('state', failure)
+ void gateway.stop(ENTRY_ID)
+}
+
+function hostOf(value: string): string | null {
+ try {
+ return new URL(value).hostname
+ }
+ catch {
+ return null
+ }
+}
+
+function note(kind: RemoteTunnelEvent['kind'], line: string): void {
+ sequence += 1
+ events = [...events, { seq: sequence, ts: new Date().toISOString(), kind, line }].slice(-EVENT_CAPACITY)
+}
diff --git a/packages/dsh-tauri-remote/src/host/service/tunnel.types.ts b/packages/dsh-tauri-remote/src/host/service/tunnel.types.ts
new file mode 100644
index 00000000..ea050d13
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/service/tunnel.types.ts
@@ -0,0 +1,20 @@
+import type { RemoteAuthPolicy, RemoteTunnelProgress } from '../types/index'
+
+export interface TunnelHandlers {
+ onLine: (line: string) => void
+ onExit: (code: number | null, signal: NodeJS.Signals | null) => void
+}
+
+export interface TunnelProcess {
+ readonly pid: number | undefined
+ readonly exited: Promise<void>
+ kill: (signal: NodeJS.Signals) => void
+}
+
+export type TunnelProgressSink = (progress: RemoteTunnelProgress) => void
+
+export interface TunnelDeps {
+ policy: () => RemoteAuthPolicy
+ resolveBinary: (onProgress?: TunnelProgressSink) => Promise<string>
+ spawn: (binary: string, args: string[], handlers: TunnelHandlers, env?: NodeJS.ProcessEnv) => TunnelProcess
+}
diff --git a/packages/dsh-tauri-ssh/src/host/storage/driver.ts b/packages/dsh-tauri-remote/src/host/storage/driver.ts
similarity index 94%
rename from packages/dsh-tauri-ssh/src/host/storage/driver.ts
rename to packages/dsh-tauri-remote/src/host/storage/driver.ts
index 440dffe2..8825561f 100644
--- a/packages/dsh-tauri-ssh/src/host/storage/driver.ts
+++ b/packages/dsh-tauri-remote/src/host/storage/driver.ts
@@ -6,9 +6,9 @@ import { stateDocumentPath } from '../config/runtime'
const DOCUMENT_KEY = 'state'
-export function sshDocumentDriver(): Driver {
+export function remoteDocumentDriver(): Driver {
return {
- name: 'dsh-tauri-ssh-document',
+ name: 'dsh-tauri-remote-document',
hasItem(key: string): boolean {
return key === DOCUMENT_KEY && readDocument() !== undefined
},
diff --git a/packages/dsh-tauri-remote/src/host/storage/index.ts b/packages/dsh-tauri-remote/src/host/storage/index.ts
new file mode 100644
index 00000000..e5128327
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/storage/index.ts
@@ -0,0 +1,4 @@
+import { createStorage } from 'unstorage'
+import { remoteDocumentDriver } from './driver'
+
+export const storage = createStorage({ driver: remoteDocumentDriver() })
diff --git a/packages/dsh-tauri-remote/src/host/types/index.ts b/packages/dsh-tauri-remote/src/host/types/index.ts
new file mode 100644
index 00000000..5e2dd935
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/types/index.ts
@@ -0,0 +1,368 @@
+import type { HostConnectionHandle } from 'dsh-tauri'
+import type { Buffer } from 'node:buffer'
+import type { IncomingMessage, ServerResponse } from 'node:http'
+
+export type MachineId = string & { readonly __machineId: unique symbol }
+
+// eslint-disable-next-line ts/no-redeclare -- 品牌类型惯用法:值与类型同名
+export function MachineId(id: string): MachineId {
+ return id as MachineId
+}
+
+export type MachineTransport = 'ssh'
+
+export interface MachineProfile {
+ id: MachineId
+ name: string
+ host: string
+ port: number
+ user: string
+ password?: string
+ passphrase?: string
+ remotePort: number
+ profileName?: string
+ startCommand?: string
+ color?: string
+ tintBorder?: boolean
+ transport?: MachineTransport
+}
+
+export interface MachineView {
+ id: MachineId
+ name: string
+ host: string
+ port: number
+ user: string
+ hasPassword: boolean
+ hasPassphrase: boolean
+ remotePort: number
+ profileName?: string
+ startCommand?: string
+ color?: string
+ tintBorder?: boolean
+}
+
+export interface MachineSaveRow {
+ name: string
+ host: string
+ port: number
+ user: string
+ remotePort: number
+ profileName?: string
+ startCommand?: string
+ color?: string
+ tintBorder?: boolean
+}
+
+export interface MachineSecretWrite {
+ password?: string
+ passphrase?: string
+}
+
+export type RemoteConnectionState
+ = | 'disconnected'
+ | 'testing'
+ | 'connecting'
+ | 'connected'
+ | 'reconnecting'
+ | 'given-up'
+
+export type RemoteAuthMethod = 'agent' | 'key' | 'password'
+
+export type RemoteProgressPhase = 'handshake' | 'starting' | 'probing' | 'installing' | 'syncing'
+
+export interface RemoteProgress {
+ phase: RemoteProgressPhase
+ attempt?: number
+ total?: number
+ item?: string
+ log?: string
+}
+
+export interface RemoteMachineStatus {
+ machineId: MachineId
+ state: RemoteConnectionState
+ tunnelBaseUrl?: string
+ lastError?: string
+ dshMissing?: boolean
+ progress?: RemoteProgress
+ nextRetryAt?: number
+ authMethod?: RemoteAuthMethod
+}
+
+export interface RemoteLink {
+ machineId: MachineId
+ tunnelBaseUrl: string
+}
+
+export type RemoteTestResult
+ = | { ok: true, banner: string }
+ | { ok: false, message: string }
+
+export type RemoteMachineStage
+ = | 'probe'
+ | 'download'
+ | 'verify'
+ | 'install'
+ | 'launch'
+ | 'ready'
+ | 'failed'
+ | 'auth'
+ | 'reconnect'
+
+export type RemoteMachineTerminal = 'success' | 'failed'
+
+export interface RemoteMachineEvent {
+ seq: number
+ ts: string
+ machineId: MachineId
+ stage: RemoteMachineStage
+ line: string
+ terminal?: RemoteMachineTerminal
+ reason?: string
+}
+
+export interface RemoteMachineEventsPage {
+ events: RemoteMachineEvent[]
+ nextSeq: number
+}
+
+export interface RemoteInstallResult {
+ installed: string[]
+ dshRef: string
+ dshVersion: string
+ dshPath: string
+ credentialsCopied: boolean
+ credentialsError?: string
+}
+
+export type RemoteErrorCode
+ = | 'machine-not-found'
+ | 'machine-connect-failed'
+ | 'machine-bootstrap-failed'
+ | 'machine-dsh-missing'
+ | 'machine-install-failed'
+ | 'machine-reconnecting'
+ | 'machine-sync-failed'
+ | 'machine-transport-unsupported'
+
+export type SyncSkillRoot = 'dsh' | 'agents'
+
+export interface SyncPluginItem {
+ name: string
+ spec: string
+ syncable: boolean
+ reason?: string
+}
+
+export interface SyncSkillItem {
+ name: string
+ root: SyncSkillRoot
+}
+
+export interface SyncPreview {
+ plugins: SyncPluginItem[]
+ skills: SyncSkillItem[]
+}
+
+export interface SyncPluginRef {
+ name: string
+ spec: string
+}
+
+export interface SyncSkillRef {
+ name: string
+ root: SyncSkillRoot
+}
+
+export interface SyncItemResult {
+ kind: 'plugin' | 'skill'
+ name: string
+ root?: SyncSkillRoot
+ ok: boolean
+ error?: string
+ log?: string
+}
+
+export interface SyncApplyResult {
+ items: SyncItemResult[]
+}
+
+export class RemoteError extends Error {
+ constructor(readonly code: RemoteErrorCode, readonly machineId: MachineId, message: string) {
+ super(message)
+ this.name = 'RemoteError'
+ }
+}
+
+export interface RemoteExecResult {
+ code: number | null
+ stdout: string
+ stderr: string
+}
+
+/** 网关来源分类:`tunnel` 只由隧道入口声明,永远按公网待遇(S2 §7.1)。 */
+export type RemoteSourceClass = 'loopback' | 'private' | 'public' | 'tunnel'
+
+/** 来源门禁三值:放行 / 需认证 / 拒绝(S2 §7.2 判定矩阵)。 */
+export type RemoteAccessDecision = 'allow' | 'authenticate' | 'deny'
+
+export type RemoteAuthScope = 'public_only' | 'all'
+
+/** 访问密码的落盘形态;`salt` 与 `hash` 均为 base64(S2 §7.4)。 */
+export interface RemotePasswordRecord {
+ algo: 'pbkdf2-sha256'
+ salt: string
+ iterations: number
+ hash: string
+}
+
+/** 认证要素快照:由持久化配置推导,每次请求重新读取,使配置变更即时生效。 */
+export interface RemoteAuthPolicy {
+ enabled: boolean
+ scope: RemoteAuthScope
+ password: RemotePasswordRecord | null
+ linkToken: string | null
+ sessionSecret: string
+ /** 当前临时配对码:与永久凭据并行的额外凭据,5 分钟轮换。 */
+ pairingCode?: string
+ consumePairingCode?: (provided: string) => boolean
+}
+
+export interface RemoteAuthFailureRecord {
+ failures: number
+ bannedUntil: number
+}
+
+export interface RemoteSessionTicket {
+ value: string
+ /** 签发时间(S2 §7.4「含签发与过期时间」);与过期时间一同被签名覆盖。 */
+ issuedAt: number
+ expiresAt: number
+}
+
+/** 公网隧道模式:`quick` 免账号随机域名;`token` 用具名隧道凭据,公开主机名由控制台指向本机口袋。 */
+export type RemoteTunnelMode = 'quick' | 'token'
+
+export type RemoteTunnelState = 'stopped' | 'starting' | 'running' | 'error'
+
+/** `access.json` 的 `tunnel` 段:只落配置,运行期状态一律内存态。 */
+export interface RemoteTunnelConfig {
+ enabled: boolean
+ mode: RemoteTunnelMode
+ token: string | null
+ hostname: string | null
+}
+
+export interface RemoteTunnelEvent {
+ seq: number
+ ts: string
+ kind: 'state' | 'process' | 'progress'
+ line: string
+}
+
+/** 隧道读面:配置(完整分支保留 `token`)+ 运行期状态;`link`/`qr` 只出现在完整分支。 */
+/** 隧道启动期进度:阶段 + 下载字节数;下载阶段带 url 便于显示正在尝试的镜像。 */
+export interface RemoteTunnelProgress {
+ stage: 'check' | 'download' | 'extract' | 'verify' | 'spawn' | 'domain' | 'ready'
+ url?: string
+ received?: number
+ total?: number
+}
+
+export interface RemoteTunnelStatus extends Omit<RemoteTunnelConfig, 'token'> {
+ state: RemoteTunnelState
+ events: RemoteTunnelEvent[]
+ token?: string
+ url?: string
+ port?: number
+ link?: string
+ qr?: string
+ progress?: RemoteTunnelProgress
+ error?: string
+}
+
+export type RemoteGatewayEntryKind = 'inbound' | 'tunnel' | 'outbound'
+
+export type RemoteGatewayEntryState = 'listening' | 'stopped'
+
+export interface RemoteGatewayEntryStatus {
+ id: string
+ kind: RemoteGatewayEntryKind
+ state: RemoteGatewayEntryState
+ host: string
+ /** 真实监听到的端口;已停止时为 0。 */
+ port: number
+ url: string
+ upstream: string
+ connections: number
+}
+
+export type RemoteGatewayEventKind = 'listening' | 'stopped' | 'port' | 'upstream' | 'cookie' | 'compression' | 'auth' | 'source'
+
+export interface RemoteGatewayEvent {
+ seq: number
+ ts: string
+ id: string
+ kind: RemoteGatewayEventKind
+ line: string
+}
+
+/**
+ * cookie 铸造的 token 提供方:每次铸造重新取用(不是一次性快照),入参为转发时使用的上游
+ * authority,返回一次性铸造 URL(附启动 token);返回 undefined 表示本次铸造放弃。
+ */
+export type RemoteGatewayTokenProvider = (authority: string) => Promise<string | undefined>
+
+export interface RemoteGatewayStartOptions {
+ id: string
+ kind: RemoteGatewayEntryKind
+ /** 上游基址:`http://127.0.0.1:<port>`。 */
+ upstream: string
+ /** 首选端口;被占用时按 +1 试探。 */
+ port: number
+ /** 监听地址;缺省 `127.0.0.1`,入站按选定网卡或 `0.0.0.0`。 */
+ host?: string
+ tokenProvider?: RemoteGatewayTokenProvider
+ auth?: () => RemoteAuthPolicy
+ /** 隧道腿的对外主机名(`host[:port]`):同源判定在 cloudflared 改写 Host 后只能靠它对 Origin / Referer。 */
+ publicHost?: () => string | undefined
+}
+
+export interface RemoteExecOptions {
+ timeoutMs?: number
+ onData?: (chunk: string) => void
+ stdinData?: Buffer
+}
+
+export interface RemoteStreamHandle {
+ localPort: number
+ close: () => Promise<void>
+}
+
+export interface RemoteSession {
+ readonly authMethod?: RemoteAuthMethod | undefined
+ exec: (command: string, options?: RemoteExecOptions) => Promise<RemoteExecResult>
+ stream: (remotePort: number, preferredLocalPort?: number) => Promise<RemoteStreamHandle>
+ onClosed: (callback: () => void) => void
+ close: () => Promise<void>
+}
+
+export interface HostWebRoute {
+ kind: 'exact' | 'prefix'
+ path: string
+ handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>
+}
+
+export interface HostWebServer {
+ register: (route: HostWebRoute) => () => void
+ /** 上游 webserver 的实监听端口(`port 0` 时为系统分配值);宿主未暴露时缺省。 */
+ port?: number
+}
+
+export interface RemoteHostContext {
+ webServer: HostWebServer
+ effect: (execute: () => (() => void) | void, label?: string) => unknown
+ connection?: HostConnectionHandle
+ logger?: { error: (message: string) => void, warn?: (message: string) => void }
+}
diff --git a/packages/dsh-tauri-ssh/src/host/utils/allowlist.test.ts b/packages/dsh-tauri-remote/src/host/utils/allowlist.test.ts
similarity index 96%
rename from packages/dsh-tauri-ssh/src/host/utils/allowlist.test.ts
rename to packages/dsh-tauri-remote/src/host/utils/allowlist.test.ts
index b3e74ae3..249e6391 100644
--- a/packages/dsh-tauri-ssh/src/host/utils/allowlist.test.ts
+++ b/packages/dsh-tauri-remote/src/host/utils/allowlist.test.ts
@@ -1,4 +1,4 @@
-import type { SshExecResult, SshSession } from '../types/index'
+import type { RemoteExecResult, RemoteSession } from '../types/index'
import { Buffer } from 'node:buffer'
import { describe, expect, it, vi } from 'vitest'
import { parse } from 'yaml'
@@ -16,16 +16,16 @@ import {
const GIT_KEY = 'dsh-better-sidebar@https://codeload.github.com/omdsh-dev/DSH-better-sidebar/tar.gz/0314fd9b93c5f55eb68f98480d84500d67a75b03'
/** A scripted session: `cat` answers the given text, writes are recorded. */
-function fakeSession(remoteText: string): SshSession & { commands: string[] } {
+function fakeSession(remoteText: string): RemoteSession & { commands: string[] } {
const commands: string[] = []
return {
commands,
exec: vi.fn(async (command: string) => {
commands.push(command)
const stdout = command.startsWith('cat ') ? remoteText : ''
- return { code: 0, stdout, stderr: '' } as SshExecResult
- }) as unknown as SshSession['exec'],
- openTunnel: () => Promise.reject(new Error('not needed')),
+ return { code: 0, stdout, stderr: '' } as RemoteExecResult
+ }) as unknown as RemoteSession['exec'],
+ stream: () => Promise.reject(new Error('not needed')),
onClosed: () => {},
close: async () => {},
}
diff --git a/packages/dsh-tauri-ssh/src/host/utils/allowlist.ts b/packages/dsh-tauri-remote/src/host/utils/allowlist.ts
similarity index 98%
rename from packages/dsh-tauri-ssh/src/host/utils/allowlist.ts
rename to packages/dsh-tauri-remote/src/host/utils/allowlist.ts
index 6cb7dd07..e23a3838 100644
--- a/packages/dsh-tauri-ssh/src/host/utils/allowlist.ts
+++ b/packages/dsh-tauri-remote/src/host/utils/allowlist.ts
@@ -1,4 +1,4 @@
-import type { SshSession } from '../types/index'
+import type { RemoteSession } from '../types/index'
import { parse, stringify } from 'yaml'
import { shQuote } from './shell'
@@ -156,7 +156,7 @@ export function allowlistWriteCommand(profileName: string, yamlText: string): st
}
export async function carryWorkspaceAllowlist(
- session: SshSession,
+ session: RemoteSession,
profileName: string,
local: WorkspaceAllowlist,
): Promise<string[]> {
diff --git a/packages/dsh-tauri-ssh/src/host/utils/assets.test.ts b/packages/dsh-tauri-remote/src/host/utils/assets.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/assets.test.ts
rename to packages/dsh-tauri-remote/src/host/utils/assets.test.ts
diff --git a/packages/dsh-tauri-ssh/src/host/utils/assets.ts b/packages/dsh-tauri-remote/src/host/utils/assets.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/assets.ts
rename to packages/dsh-tauri-remote/src/host/utils/assets.ts
diff --git a/packages/dsh-tauri-remote/src/host/utils/auth.test.ts b/packages/dsh-tauri-remote/src/host/utils/auth.test.ts
new file mode 100644
index 00000000..0ab8cbea
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/utils/auth.test.ts
@@ -0,0 +1,189 @@
+import type { RemotePasswordRecord } from '../types/index'
+import { describe, expect, it } from 'vitest'
+import { createLinkToken, createSessionSecret, hashPassword, isPasswordRecordUsable, rateLimitAfterFailure, rateLimitBlockedMs, signSession, tokenMatches, verifyPassword, verifySession } from './auth'
+
+const ITERATIONS = 1000
+
+const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000
+
+const FAILURE_LIMIT = 5
+
+const BAN_MS = 5 * 60 * 1000
+
+function recordOf(password: string): RemotePasswordRecord {
+ return hashPassword(password, ITERATIONS)
+}
+
+describe('hashPassword', () => {
+ it('produces a pbkdf2-sha256 record with the configured iteration count', () => {
+ const record = recordOf('correct horse')
+ expect(record.algo).toBe('pbkdf2-sha256')
+ expect(record.iterations).toBe(ITERATIONS)
+ expect(record.salt).not.toBe('')
+ expect(record.hash).not.toBe('')
+ })
+
+ it('defaults to the pinned iteration constant', () => {
+ expect(hashPassword('correct horse')).toMatchObject({ iterations: 600_000 })
+ })
+
+ it('salts every record independently, so the same password hashes differently', () => {
+ expect(recordOf('correct horse').hash).not.toBe(recordOf('correct horse').hash)
+ expect(recordOf('correct horse').salt).not.toBe(recordOf('correct horse').salt)
+ })
+})
+
+describe('verifyPassword', () => {
+ it('accepts the exact password and rejects any other', () => {
+ const record = recordOf('correct horse')
+ expect(verifyPassword('correct horse', record)).toBe(true)
+ expect(verifyPassword('correct hors', record)).toBe(false)
+ expect(verifyPassword('correct horse ', record)).toBe(false)
+ expect(verifyPassword('Correct horse', record)).toBe(false)
+ expect(verifyPassword('', record)).toBe(false)
+ })
+
+ it('rejects a record that carries no password at all', () => {
+ expect(verifyPassword('correct horse', null)).toBe(false)
+ })
+
+ it.each([
+ { algo: 'pbkdf2-sha256', salt: 'not-base64!', iterations: ITERATIONS, hash: 'aGFzaA==' },
+ { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: ITERATIONS, hash: 'not-base64!' },
+ { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 0, hash: 'aGFzaA==' },
+ { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 1.5, hash: 'aGFzaA==' },
+ { algo: 'scrypt', salt: 'c2FsdA==', iterations: ITERATIONS, hash: 'aGFzaA==' },
+ ])('treats the corrupted record %j as unverifiable instead of throwing', (record) => {
+ expect(verifyPassword('correct horse', record as unknown as RemotePasswordRecord)).toBe(false)
+ })
+})
+
+describe('isPasswordRecordUsable', () => {
+ it('accepts a freshly hashed record and rejects a missing one', () => {
+ expect(isPasswordRecordUsable(recordOf('correct horse'))).toBe(true)
+ expect(isPasswordRecordUsable(null)).toBe(false)
+ })
+
+ it.each([
+ { algo: 'pbkdf2-sha256', salt: 'not-base64!', iterations: ITERATIONS, hash: 'aGFzaA==' },
+ { algo: 'pbkdf2-sha256', salt: '', iterations: ITERATIONS, hash: 'aGFzaA==' },
+ { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: ITERATIONS, hash: 'not-base64!' },
+ { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: ITERATIONS, hash: 'aGFzaA==' },
+ { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 0, hash: 'aGFzaA==' },
+ { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: -1, hash: 'aGFzaA==' },
+ { algo: 'scrypt', salt: 'c2FsdA==', iterations: ITERATIONS, hash: 'aGFzaA==' },
+ ])('rejects the corrupted record %j', (record) => {
+ expect(isPasswordRecordUsable(record as unknown as RemotePasswordRecord)).toBe(false)
+ })
+})
+
+describe('signSession / verifySession', () => {
+ const SECRET = createSessionSecret()
+
+ it('round-trips a freshly signed session and reports its issue and expiry times', () => {
+ const now = 1_700_000_000_000
+ const ticket = signSession(SECRET, now)
+ expect(ticket.issuedAt).toBe(now)
+ expect(ticket.expiresAt).toBe(now + SESSION_TTL_MS)
+ expect(ticket.value.split('.')).toEqual([expect.any(String), String(now), String(now + SESSION_TTL_MS), expect.any(String)])
+ expect(verifySession(ticket.value, SECRET, now)).toBe(true)
+ expect(verifySession(ticket.value, SECRET, ticket.expiresAt - 1)).toBe(true)
+ })
+
+ it('rejects an expired session', () => {
+ const now = 1_700_000_000_000
+ const ticket = signSession(SECRET, now, 1000)
+ expect(verifySession(ticket.value, SECRET, now + 1001)).toBe(false)
+ expect(verifySession(ticket.value, SECRET, now + 1000)).toBe(false)
+ })
+
+ it('rejects a tampered expiry, a tampered issue time, a tampered signature and a foreign secret', () => {
+ const now = 1_700_000_000_000
+ const ticket = signSession(SECRET, now)
+ const [version, , , mac] = ticket.value.split('.')
+ expect(verifySession(`${version}.${now + 999_999}.${now + 999_999}.${mac}`, SECRET, now)).toBe(false)
+ expect(verifySession(`${version}.${now - 1}.${now + SESSION_TTL_MS}.${mac}`, SECRET, now)).toBe(false)
+ expect(verifySession(`${ticket.value}x`, SECRET, now)).toBe(false)
+ expect(verifySession(`${version}.${now}.${now + SESSION_TTL_MS}.${mac?.toUpperCase()}`, SECRET, now)).toBe(false)
+ expect(verifySession(ticket.value, createSessionSecret(), now)).toBe(false)
+ })
+
+ it.each([undefined, '', 'v1', 'v1.123', 'v1.123.456', 'v2.1.9999999999999.abc', 'v1.abc.def.ghi'])('rejects the malformed session value %j', (value) => {
+ expect(verifySession(value, SECRET, 1_700_000_000_000)).toBe(false)
+ })
+
+ it('refuses to verify anything while no secret is configured', () => {
+ expect(verifySession(signSession(SECRET, 1).value, '', 0)).toBe(false)
+ })
+})
+
+describe('createLinkToken', () => {
+ it('generates eight uppercase letters or digits without ambiguous characters', () => {
+ for (let index = 0; index < 32; index++)
+ expect(createLinkToken()).toMatch(/^[2-9A-HJ-NP-Z]{8}$/u)
+ })
+})
+
+describe('tokenMatches', () => {
+ it('ignores letter case only for the new eight-character codes', () => {
+ expect(tokenMatches('AB23CD45', 'AB23CD45')).toBe(true)
+ expect(tokenMatches('ab23cd45', 'AB23CD45')).toBe(true)
+ expect(tokenMatches('aB23cD45', 'AB23CD45')).toBe(true)
+ expect(tokenMatches('ab23cd46', 'AB23CD45')).toBe(false)
+ expect(tokenMatches('ab23cd45x', 'AB23CD45')).toBe(false)
+ expect(tokenMatches('b23cd45', 'AB23CD45')).toBe(false)
+ expect(tokenMatches('ab23cd45 ', 'AB23CD45')).toBe(false)
+ expect(tokenMatches('AB2ſCD45', 'AB2SCD45')).toBe(false)
+ })
+
+ it('keeps legacy tokens and other strings case-sensitive', () => {
+ const legacy = 'AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCdE'
+ expect(legacy).toHaveLength(43)
+ expect(tokenMatches(legacy, legacy)).toBe(true)
+ expect(tokenMatches(legacy.toLowerCase(), legacy)).toBe(false)
+ expect(tokenMatches('ab23cd45', 'ab23cd45')).toBe(true)
+ expect(tokenMatches('AB23CD45', 'ab23cd45')).toBe(false)
+ expect(tokenMatches('LINK-TOKEN', 'link-token')).toBe(false)
+ expect(tokenMatches('abc01234', 'ABC01234')).toBe(false)
+ expect(tokenMatches('01234567', '01234567')).toBe(true)
+ })
+
+ it('rejects a missing token or a configuration without one', () => {
+ expect(tokenMatches(undefined, 'token')).toBe(false)
+ expect(tokenMatches('token', null)).toBe(false)
+ expect(tokenMatches('token', '')).toBe(false)
+ expect(tokenMatches('', 'token')).toBe(false)
+ })
+})
+
+describe('rate limiting', () => {
+ const NOW = 1_700_000_000_000
+
+ it('counts failures without banning below the threshold', () => {
+ let record = rateLimitAfterFailure(undefined, NOW)
+ expect(record).toEqual({ failures: 1, bannedUntil: 0 })
+ for (let index = 2; index < FAILURE_LIMIT; index++)
+ record = rateLimitAfterFailure(record, NOW)
+ expect(record).toEqual({ failures: FAILURE_LIMIT - 1, bannedUntil: 0 })
+ expect(rateLimitBlockedMs(record, NOW)).toBe(0)
+ })
+
+ it('bans for the configured duration when the threshold is reached', () => {
+ let record = rateLimitAfterFailure(undefined, NOW)
+ for (let index = 1; index < FAILURE_LIMIT; index++)
+ record = rateLimitAfterFailure(record, NOW)
+ expect(record.bannedUntil).toBe(NOW + BAN_MS)
+ expect(rateLimitBlockedMs(record, NOW)).toBe(BAN_MS)
+ expect(rateLimitBlockedMs(record, NOW + BAN_MS)).toBe(0)
+ })
+
+ it('restarts the failure count once the ban has expired', () => {
+ const banned = { failures: 0, bannedUntil: NOW + BAN_MS }
+ expect(rateLimitAfterFailure(banned, NOW + BAN_MS + 1)).toEqual({ failures: 1, bannedUntil: 0 })
+ expect(rateLimitAfterFailure(banned, NOW + 1)).toEqual({ failures: 1, bannedUntil: 0 })
+ })
+
+ it('reports no block for an unknown bucket', () => {
+ expect(rateLimitBlockedMs(undefined, NOW)).toBe(0)
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/host/utils/auth.ts b/packages/dsh-tauri-remote/src/host/utils/auth.ts
new file mode 100644
index 00000000..f3e09671
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/utils/auth.ts
@@ -0,0 +1,131 @@
+import type { RemoteAuthFailureRecord, RemotePasswordRecord, RemoteSessionTicket } from '../types/index'
+import { Buffer } from 'node:buffer'
+import { createHmac, pbkdf2Sync, randomBytes, randomInt, timingSafeEqual } from 'node:crypto'
+
+const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000
+
+const AUTH_FAILURE_LIMIT = 5
+
+const AUTH_BAN_MS = 5 * 60 * 1000
+
+/** OWASP 对 PBKDF2-SHA256 的现行建议下限(本机实测约 48ms/次)。 */
+const PBKDF2_ITERATIONS = 600_000
+
+const HASH_BYTES = 32
+
+const SALT_BYTES = 16
+
+const SECRET_BYTES = 32
+
+const PASSWORD_LENGTH = 20
+
+const LINK_TOKEN_LENGTH = 8
+
+const LINK_TOKEN_ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'
+
+const SESSION_VERSION = 'v1'
+
+export function hashPassword(password: string, iterations = PBKDF2_ITERATIONS): RemotePasswordRecord {
+ const salt = randomBytes(SALT_BYTES)
+ return {
+ algo: 'pbkdf2-sha256',
+ salt: salt.toString('base64'),
+ iterations,
+ hash: derive(password, salt, iterations).toString('base64'),
+ }
+}
+
+export function verifyPassword(password: string, record: RemotePasswordRecord | null): boolean {
+ const usable = usablePasswordOf(record)
+ return usable !== undefined && matches(derive(password, usable.salt, usable.iterations), usable.hash)
+}
+
+/** 密码记录可用性:算法、迭代次数、salt 与 hash 编码及长度全部合规才可用(S2 §11 的损坏判定复用同一份规则)。 */
+export function isPasswordRecordUsable(record: RemotePasswordRecord | null): record is RemotePasswordRecord {
+ return usablePasswordOf(record) !== undefined
+}
+
+export function signSession(secret: string, now: number, ttlMs = SESSION_TTL_MS): RemoteSessionTicket {
+ const expiresAt = now + ttlMs
+ return { value: `${SESSION_VERSION}.${now}.${expiresAt}.${signatureOf(secret, now, expiresAt)}`, issuedAt: now, expiresAt }
+}
+
+export function verifySession(value: string | undefined, secret: string, now: number): boolean {
+ if (value === undefined || secret === '')
+ return false
+ const segments = value.split('.')
+ const version = segments[0]
+ const issuedAt = Number(segments[1])
+ const expiresAt = Number(segments[2])
+ const mac = segments[3]
+ if (segments.length !== 4 || version !== SESSION_VERSION || mac === undefined || !Number.isInteger(issuedAt) || !Number.isInteger(expiresAt) || expiresAt <= now)
+ return false
+ return matches(Buffer.from(signatureOf(secret, issuedAt, expiresAt)), Buffer.from(mac))
+}
+
+export function createLinkToken(): string {
+ return Array.from({ length: LINK_TOKEN_LENGTH }, () => LINK_TOKEN_ALPHABET[randomInt(LINK_TOKEN_ALPHABET.length)]).join('')
+}
+
+export function generateAccessPassword(length = PASSWORD_LENGTH): string {
+ const alphabet = '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
+ const bytes = randomBytes(length)
+ let password = ''
+ for (const byte of bytes)
+ password += alphabet[byte % alphabet.length]
+ return password
+}
+
+export function createSessionSecret(): string {
+ return randomBytes(SECRET_BYTES).toString('base64url')
+}
+
+export function tokenMatches(provided: string | undefined, expected: string | null): boolean {
+ if (provided === undefined || expected === null || expected === '')
+ return false
+ const candidate = /^[2-9A-HJ-NP-Z]{8}$/u.test(expected) && /^[2-9A-HJ-NP-Za-hj-np-z]{8}$/u.test(provided) ? provided.toUpperCase() : provided
+ return matches(Buffer.from(candidate), Buffer.from(expected))
+}
+
+export function rateLimitAfterFailure(
+ record: RemoteAuthFailureRecord | undefined,
+ now: number,
+ limit = AUTH_FAILURE_LIMIT,
+ banMs = AUTH_BAN_MS,
+): RemoteAuthFailureRecord {
+ const base = record === undefined || (record.bannedUntil > 0 && record.bannedUntil <= now) ? 0 : record.failures
+ const failures = base + 1
+ return failures >= limit ? { failures: 0, bannedUntil: now + banMs } : { failures, bannedUntil: 0 }
+}
+
+export function rateLimitBlockedMs(record: RemoteAuthFailureRecord | undefined, now: number): number {
+ return record === undefined ? 0 : Math.max(0, record.bannedUntil - now)
+}
+
+// --- internal ---
+function usablePasswordOf(record: RemotePasswordRecord | null): { salt: Buffer, hash: Buffer, iterations: number } | undefined {
+ if (record === null || record.algo !== 'pbkdf2-sha256' || !Number.isInteger(record.iterations) || record.iterations <= 0)
+ return undefined
+ const salt = decodeBase64(record.salt)
+ const hash = decodeBase64(record.hash)
+ if (salt === undefined || salt.length === 0 || hash === undefined || hash.length !== HASH_BYTES)
+ return undefined
+ return { salt, hash, iterations: record.iterations }
+}
+
+function derive(password: string, salt: Buffer, iterations: number): Buffer {
+ return pbkdf2Sync(password, salt, iterations, HASH_BYTES, 'sha256')
+}
+
+function signatureOf(secret: string, issuedAt: number, expiresAt: number): string {
+ return createHmac('sha256', secret).update(`${SESSION_VERSION}.${issuedAt}.${expiresAt}`).digest('hex')
+}
+
+function matches(left: Buffer, right: Buffer): boolean {
+ return left.length === right.length && timingSafeEqual(left, right)
+}
+
+function decodeBase64(value: string): Buffer | undefined {
+ const decoded = Buffer.from(value, 'base64')
+ return decoded.toString('base64') === value ? decoded : undefined
+}
diff --git a/packages/dsh-tauri-ssh/src/host/utils/boot-html.test.ts b/packages/dsh-tauri-remote/src/host/utils/boot-html.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/boot-html.test.ts
rename to packages/dsh-tauri-remote/src/host/utils/boot-html.test.ts
diff --git a/packages/dsh-tauri-ssh/src/host/utils/boot-html.ts b/packages/dsh-tauri-remote/src/host/utils/boot-html.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/boot-html.ts
rename to packages/dsh-tauri-remote/src/host/utils/boot-html.ts
diff --git a/packages/dsh-tauri-remote/src/host/utils/cloudflared.test.ts b/packages/dsh-tauri-remote/src/host/utils/cloudflared.test.ts
new file mode 100644
index 00000000..20cee097
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/utils/cloudflared.test.ts
@@ -0,0 +1,117 @@
+import { Buffer } from 'node:buffer'
+import { existsSync, mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'pathe'
+import { describe, expect, it } from 'vitest'
+import { cloudflaredAsset, cloudflaredDownloadUrls, fetchCloudflaredRelease, isCloudflaredVersion, parseQuickTunnelUrl, quickTunnelArgs, resolveCloudflared, tokenTunnelArgs, tokenTunnelEnv } from './cloudflared'
+
+describe('cloudflared 平台表', () => {
+ it('覆盖受支持的平台组合', () => {
+ expect(cloudflaredAsset('darwin', 'arm64')).toEqual({ asset: 'cloudflared-darwin-arm64.tgz', executable: 'cloudflared', archive: true })
+ expect(cloudflaredAsset('darwin', 'x64')).toEqual({ asset: 'cloudflared-darwin-amd64.tgz', executable: 'cloudflared', archive: true })
+ expect(cloudflaredAsset('linux', 'x64')).toEqual({ asset: 'cloudflared-linux-amd64', executable: 'cloudflared', archive: false })
+ expect(cloudflaredAsset('linux', 'arm64')).toEqual({ asset: 'cloudflared-linux-arm64', executable: 'cloudflared', archive: false })
+ expect(cloudflaredAsset('win32', 'x64')).toEqual({ asset: 'cloudflared-windows-amd64.exe', executable: 'cloudflared.exe', archive: false })
+ })
+
+ it('不支持的平台没有资产,调用方据此给出可读错误', () => {
+ expect(cloudflaredAsset('linux', 'arm')).toBeUndefined()
+ expect(cloudflaredAsset('freebsd', 'x64')).toBeUndefined()
+ })
+})
+
+describe('下载源与命令行', () => {
+ it('按已解析的 tag 拼官方直链,镜像前缀透传原地址', () => {
+ const urls = cloudflaredDownloadUrls('cloudflared-linux-amd64', '2026.10.0')
+ expect(urls).toEqual([
+ 'https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-linux-amd64',
+ 'https://ghfast.top/https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-linux-amd64',
+ ])
+ })
+
+ it('cLOUDFLARED_VERSION 固定版本时地址与摘要都按该版本取', () => {
+ const urls = cloudflaredDownloadUrls('cloudflared-darwin-arm64.tgz', '2026.10.0', '2026.9.0')
+ expect(urls[0]).toBe('https://github.com/cloudflare/cloudflared/releases/download/2026.9.0/cloudflared-darwin-arm64.tgz')
+ })
+
+ it('官方发布元数据缺失 sha256 摘要时拒绝执行', async () => {
+ const original = globalThis.fetch
+ globalThis.fetch = (async () => new Response(JSON.stringify({ tag_name: '2026.10.0', assets: [{ name: 'cloudflared-linux-amd64', size: 1 }] }), { status: 200 })) as typeof fetch
+ try {
+ await expect(fetchCloudflaredRelease('cloudflared-linux-amd64')).rejects.toThrow('sha256')
+ }
+ finally {
+ globalThis.fetch = original
+ }
+ })
+
+ it('官方发布元数据解析出 tag 与摘要', async () => {
+ const original = globalThis.fetch
+ const digest = `sha256:${'a'.repeat(64)}`
+ globalThis.fetch = (async () => new Response(JSON.stringify({ tag_name: '2026.10.0', assets: [{ name: 'cloudflared-linux-amd64', digest, size: 42 }] }), { status: 200 })) as typeof fetch
+ try {
+ await expect(fetchCloudflaredRelease('cloudflared-linux-amd64')).resolves.toEqual({ tag: '2026.10.0', digest, size: 42 })
+ }
+ finally {
+ globalThis.fetch = original
+ }
+ })
+
+ it('quick 模式指向本机隧道入口且关闭自动更新', () => {
+ expect(quickTunnelArgs('http://127.0.0.1:3089')).toEqual(['tunnel', '--no-autoupdate', '--url', 'http://127.0.0.1:3089'])
+ })
+
+ it('具名隧道的凭据走环境变量,不出现在进程参数里', () => {
+ expect(tokenTunnelArgs()).toEqual(['tunnel', '--no-autoupdate', 'run'])
+ expect(tokenTunnelEnv('cf-token')).toEqual({ TUNNEL_TOKEN: 'cf-token' })
+ expect(tokenTunnelArgs().join(' ')).not.toContain('cf-token')
+ })
+})
+
+describe('下载校验', () => {
+ it('摘要不匹配时拒绝执行,且不写出可执行文件', async () => {
+ const originalFetch = globalThis.fetch
+ const home = mkdtempSync(join(tmpdir(), 'dsh-cloudflared-verify-'))
+ const previousHome = process.env.DSH_HOME
+ process.env.DSH_HOME = home
+ globalThis.fetch = (async (input: string | URL) => {
+ const url = String(input)
+ if (url.includes('api.github.com'))
+ return new Response(JSON.stringify({ tag_name: '2026.10.0', assets: [{ name: cloudflaredAsset()?.asset, digest: `sha256:${'f'.repeat(64)}`, size: 4 }] }), { status: 200 })
+ return new Response(Buffer.from('junk'), { status: 200, headers: { 'content-length': '4' } })
+ }) as typeof fetch
+ try {
+ await expect(resolveCloudflared()).rejects.toThrow('SHA-256 校验失败')
+ expect(existsSync(join(home, 'remote', 'bin', cloudflaredAsset()?.executable ?? ''))).toBe(false)
+ }
+ finally {
+ globalThis.fetch = originalFetch
+ if (previousHome === undefined)
+ delete process.env.DSH_HOME
+ else
+ process.env.DSH_HOME = previousHome
+ rmSync(home, { recursive: true, force: true })
+ }
+ }, 30_000)
+})
+
+describe('日志解析', () => {
+ it('从 cloudflared 的日志行里取出 quick 隧道域名', () => {
+ expect(parseQuickTunnelUrl('INF Your quick Tunnel has been created! Visit it at https://bold-fox-abc.trycloudflare.com'))
+ .toBe('https://bold-fox-abc.trycloudflare.com')
+ expect(parseQuickTunnelUrl('INF | https://plain-host.trycloudflare.com |')).toBe('https://plain-host.trycloudflare.com')
+ })
+
+ it('不把其它地址当隧道域名', () => {
+ expect(parseQuickTunnelUrl('INF Cannot reach https://api.cloudflare.com/client/v4')).toBeUndefined()
+ expect(parseQuickTunnelUrl('INF http://bold-fox-abc.trycloudflare.com')).toBeUndefined()
+ expect(parseQuickTunnelUrl('INF Requesting new quick Tunnel on trycloudflare.com...')).toBeUndefined()
+ })
+
+ it('只认 cloudflared 的版本行', () => {
+ expect(isCloudflaredVersion('cloudflared version 2026.1.0 (built 2026-01-02-1200)')).toBe(true)
+ expect(isCloudflaredVersion('cloudflared version 2026.1.0')).toBe(true)
+ expect(isCloudflaredVersion('command not found: cloudflared')).toBe(false)
+ expect(isCloudflaredVersion('cloudflared version unknown')).toBe(false)
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/host/utils/cloudflared.ts b/packages/dsh-tauri-remote/src/host/utils/cloudflared.ts
new file mode 100644
index 00000000..8f8f581a
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/utils/cloudflared.ts
@@ -0,0 +1,258 @@
+import type { TunnelHandlers, TunnelProcess } from '../service/tunnel.types'
+import { Buffer } from 'node:buffer'
+import { execFile, spawn } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import process from 'node:process'
+import { promisify } from 'node:util'
+import { dirname, join } from 'pathe'
+import { messageOf } from '../../shared/error'
+import { harnessHome } from '../config/runtime'
+
+const execFileAsync = promisify(execFile)
+
+const RELEASE_BASE = 'https://github.com/cloudflare/cloudflared/releases/download/'
+
+const RELEASE_API = 'https://api.github.com/repos/cloudflare/cloudflared/releases/latest'
+
+const RELEASE_TIMEOUT_MS = 20_000
+
+const MIRROR_PREFIX = 'https://ghfast.top/'
+
+const STATE_DIR = 'remote'
+const BIN_DIR = 'bin'
+
+const DOWNLOAD_TIMEOUT_MS = 120_000
+const VERSION_TIMEOUT_MS = 5_000
+const EXTRACT_TIMEOUT_MS = 60_000
+
+const RE_VERSION = /^cloudflared version \d+\.\d+\.\d+/m
+const RE_QUICK_URL = /https:\/\/[a-z0-9][a-z0-9-]*\.trycloudflare\.com/
+
+/** 二进制准备阶段的进度:面板据此显示「下载中 x%」而不是静默等待。 */
+export interface CloudflaredProgress {
+ stage: 'check' | 'download' | 'extract' | 'verify'
+ url?: string
+ received?: number
+ total?: number
+}
+
+export type CloudflaredProgressSink = (progress: CloudflaredProgress) => void
+
+export interface CloudflaredAsset {
+ asset: string
+ executable: string
+ archive: boolean
+}
+
+const ASSETS: Record<string, CloudflaredAsset> = {
+ 'darwin-arm64': { asset: 'cloudflared-darwin-arm64.tgz', executable: 'cloudflared', archive: true },
+ 'darwin-x64': { asset: 'cloudflared-darwin-amd64.tgz', executable: 'cloudflared', archive: true },
+ 'linux-x64': { asset: 'cloudflared-linux-amd64', executable: 'cloudflared', archive: false },
+ 'linux-arm64': { asset: 'cloudflared-linux-arm64', executable: 'cloudflared', archive: false },
+ 'win32-x64': { asset: 'cloudflared-windows-amd64.exe', executable: 'cloudflared.exe', archive: false },
+}
+
+export function cloudflaredAsset(platform: string = process.platform, arch: string = process.arch): CloudflaredAsset | undefined {
+ return ASSETS[`${platform}-${arch}`]
+}
+
+/** 候选下载地址:官方 tag 直链优先,镜像只做传输兜底;两者都用同一份官方摘要校验。 */
+export function cloudflaredDownloadUrls(asset: string, tag: string, version?: string): string[] {
+ const resolved = version === undefined || version === '' ? tag : version
+ const primary = `${RELEASE_BASE}${resolved}/${asset}`
+ return [primary, `${MIRROR_PREFIX}${primary}`]
+}
+
+/** 官方发布的资产摘要:`sha256:` 前缀来自 GitHub Release API,与资产一一对应。 */
+export interface CloudflaredRelease {
+ tag: string
+ digest: string
+ size?: number
+}
+
+export async function fetchCloudflaredRelease(asset: string, version?: string): Promise<CloudflaredRelease> {
+ const url = version === undefined || version === '' ? RELEASE_API : `https://api.github.com/repos/cloudflare/cloudflared/releases/tags/${version}`
+ const response = await fetch(url, { signal: AbortSignal.timeout(RELEASE_TIMEOUT_MS), headers: { accept: 'application/vnd.github+json' } })
+ if (!response.ok)
+ throw new Error(`发布元数据不可用(HTTP ${response.status})`)
+ const body = await response.json() as { tag_name?: unknown, assets?: unknown }
+ const tag = typeof body.tag_name === 'string' ? body.tag_name : ''
+ const entries = Array.isArray(body.assets) ? body.assets : []
+ const found = entries.find((entry): entry is { digest?: unknown, size?: unknown } => typeof entry === 'object' && entry !== null && (entry as { name?: unknown }).name === asset)
+ const digest = typeof found?.digest === 'string' ? found.digest : ''
+ if (tag === '' || !/^sha256:[0-9a-f]{64}$/.test(digest))
+ throw new Error(`官方未提供 ${asset} 的 sha256 摘要,拒绝执行未校验的二进制`)
+ return { tag, digest, ...typeof found?.size === 'number' ? { size: found.size } : {} }
+}
+
+export function quickTunnelArgs(entryUrl: string): string[] {
+ return ['tunnel', '--no-autoupdate', '--url', entryUrl]
+}
+
+/** 具名隧道:凭据经 `TUNNEL_TOKEN` 环境变量传入,避免出现在进程参数(`ps` 可见)里。 */
+export function tokenTunnelArgs(): string[] {
+ return ['tunnel', '--no-autoupdate', 'run']
+}
+
+export function tokenTunnelEnv(token: string): NodeJS.ProcessEnv {
+ return { TUNNEL_TOKEN: token }
+}
+
+export function parseQuickTunnelUrl(line: string): string | undefined {
+ return RE_QUICK_URL.exec(line)?.[0]
+}
+
+export function isCloudflaredVersion(output: string): boolean {
+ return RE_VERSION.test(output)
+}
+
+/** PATH 优先、数据目录次之、最后按平台下载;失败原因一律可读(含尝试过的地址)。 */
+export async function resolveCloudflared(onProgress?: CloudflaredProgressSink): Promise<string> {
+ onProgress?.({ stage: 'check' })
+ const override = process.env.CLOUDFLARED_PATH
+ if (override !== undefined && override.trim() !== '') {
+ if (await runsCloudflared(override.trim()))
+ return override.trim()
+ throw new Error(`CLOUDFLARED_PATH 指向的可执行文件不可用:${override.trim()}`)
+ }
+ if (await runsCloudflared('cloudflared'))
+ return 'cloudflared'
+ const target = installedBinaryPath()
+ if (existsSync(target) && await runsCloudflared(target))
+ return target
+ return await downloadCloudflared(target, onProgress)
+}
+
+export function spawnCloudflared(binary: string, args: string[], handlers: TunnelHandlers, env?: NodeJS.ProcessEnv): TunnelProcess {
+ const child = spawn(binary, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, ...env === undefined ? {} : { env: { ...process.env, ...env } } })
+ const exited = new Promise<void>((resolve) => {
+ child.once('exit', (code, signal) => {
+ handlers.onExit(code, signal)
+ resolve()
+ })
+ })
+ consumeLines(child.stdout, handlers.onLine)
+ consumeLines(child.stderr, handlers.onLine)
+ return {
+ pid: child.pid,
+ exited,
+ kill: (signal) => {
+ if (process.platform === 'win32' && child.pid !== undefined) {
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
+ return
+ }
+ child.kill(signal)
+ },
+ }
+}
+
+// --- internal ---
+function installedBinaryPath(): string {
+ const asset = cloudflaredAsset()
+ if (asset === undefined)
+ throw new Error(`不支持的平台:${process.platform}-${process.arch};请自行安装 cloudflared 并设置 CLOUDFLARED_PATH`)
+ return join(harnessHome(), STATE_DIR, BIN_DIR, asset.executable)
+}
+
+async function runsCloudflared(binary: string): Promise<boolean> {
+ try {
+ const { stdout, stderr } = await execFileAsync(binary, ['--version'], { timeout: VERSION_TIMEOUT_MS })
+ return isCloudflaredVersion(`${stdout}\n${stderr}`)
+ }
+ catch {
+ return false
+ }
+}
+
+async function downloadCloudflared(target: string, onProgress?: CloudflaredProgressSink): Promise<string> {
+ const asset = cloudflaredAsset()
+ if (asset === undefined)
+ throw new Error(`不支持的平台:${process.platform}-${process.arch};请自行安装 cloudflared 并设置 CLOUDFLARED_PATH`)
+ const release = await fetchCloudflaredRelease(asset.asset, process.env.CLOUDFLARED_VERSION)
+ const expected = release.digest.slice('sha256:'.length)
+ const failures: string[] = []
+ for (const url of cloudflaredDownloadUrls(asset.asset, release.tag, process.env.CLOUDFLARED_VERSION)) {
+ try {
+ onProgress?.({ stage: 'download', url, received: 0, ...release.size === undefined ? {} : { total: release.size } })
+ await downloadInto(url, asset, target, expected, onProgress)
+ onProgress?.({ stage: 'verify' })
+ if (!await runsCloudflared(target))
+ throw new Error('下载完成但 --version 自检失败')
+ return target
+ }
+ catch (error) {
+ failures.push(`${url} → ${messageOf(error)}`)
+ }
+ }
+ throw new Error(`cloudflared 下载失败(已尝试:${failures.join(';')};官方摘要 ${release.digest});可手工安装后放到 ${target} 或设置 CLOUDFLARED_PATH`)
+}
+
+async function downloadInto(url: string, asset: CloudflaredAsset, target: string, expectedSha256: string, onProgress?: CloudflaredProgressSink): Promise<void> {
+ const response = await fetch(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS), redirect: 'follow' })
+ if (!response.ok)
+ throw new Error(`HTTP ${response.status}`)
+ const declared = Number(response.headers.get('content-length') ?? '')
+ const total = Number.isFinite(declared) && declared > 0 ? declared : undefined
+ const chunks: Buffer[] = []
+ let received = 0
+ if (response.body === null) {
+ const body = Buffer.from(await response.arrayBuffer())
+ chunks.push(body)
+ received = body.length
+ }
+ else {
+ const reader = response.body.getReader()
+ while (true) {
+ const step = await reader.read()
+ if (step.done)
+ break
+ const chunk = Buffer.from(step.value)
+ chunks.push(chunk)
+ received += chunk.length
+ onProgress?.({ stage: 'download', url, received, ...total === undefined ? {} : { total } })
+ }
+ }
+ const body = Buffer.concat(chunks)
+ if (body.length === 0)
+ throw new Error('响应为空')
+ const actual = createHash('sha256').update(body).digest('hex')
+ if (actual !== expectedSha256)
+ throw new Error(`SHA-256 校验失败(期望 ${expectedSha256},实际 ${actual}),已丢弃该文件`)
+ mkdirSync(dirname(target), { recursive: true, mode: 0o700 })
+ if (!asset.archive) {
+ writeFileSync(target, body)
+ chmodSync(target, 0o755)
+ return
+ }
+ onProgress?.({ stage: 'extract', url })
+ const staging = mkdtempSync(join(tmpdir(), 'dsh-cloudflared-'))
+ try {
+ const archive = join(staging, asset.asset)
+ writeFileSync(archive, body)
+ await execFileAsync('tar', ['-xzf', archive, '-C', staging, asset.executable], { timeout: EXTRACT_TIMEOUT_MS })
+ const extracted = join(staging, asset.executable)
+ if (!existsSync(extracted))
+ throw new Error(`压缩包内没有 ${asset.executable}`)
+ writeFileSync(target, readFileSync(extracted))
+ chmodSync(target, 0o755)
+ }
+ finally {
+ rmSync(staging, { recursive: true, force: true })
+ }
+}
+
+function consumeLines(stream: NodeJS.ReadableStream | null, listener: (line: string) => void): void {
+ if (stream === null)
+ return
+ let pending = ''
+ stream.setEncoding('utf8')
+ stream.on('data', (chunk: string) => {
+ pending += chunk
+ const lines = pending.split('\n')
+ pending = lines.pop() ?? ''
+ for (const line of lines)
+ listener(line)
+ })
+}
diff --git a/packages/dsh-tauri-ssh/src/host/utils/fixtures/garbage.txt b/packages/dsh-tauri-remote/src/host/utils/fixtures/garbage.txt
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/fixtures/garbage.txt
rename to packages/dsh-tauri-remote/src/host/utils/fixtures/garbage.txt
diff --git a/packages/dsh-tauri-ssh/src/host/utils/fixtures/id_ed25519 b/packages/dsh-tauri-remote/src/host/utils/fixtures/id_ed25519
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/fixtures/id_ed25519
rename to packages/dsh-tauri-remote/src/host/utils/fixtures/id_ed25519
diff --git a/packages/dsh-tauri-ssh/src/host/utils/fixtures/id_ed25519.pub b/packages/dsh-tauri-remote/src/host/utils/fixtures/id_ed25519.pub
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/fixtures/id_ed25519.pub
rename to packages/dsh-tauri-remote/src/host/utils/fixtures/id_ed25519.pub
diff --git a/packages/dsh-tauri-ssh/src/host/utils/fixtures/id_ed25519_enc b/packages/dsh-tauri-remote/src/host/utils/fixtures/id_ed25519_enc
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/fixtures/id_ed25519_enc
rename to packages/dsh-tauri-remote/src/host/utils/fixtures/id_ed25519_enc
diff --git a/packages/dsh-tauri-ssh/src/host/utils/fixtures/id_rsa.pub b/packages/dsh-tauri-remote/src/host/utils/fixtures/id_rsa.pub
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/fixtures/id_rsa.pub
rename to packages/dsh-tauri-remote/src/host/utils/fixtures/id_rsa.pub
diff --git a/packages/dsh-tauri-ssh/src/host/utils/local.test.ts b/packages/dsh-tauri-remote/src/host/utils/local.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/local.test.ts
rename to packages/dsh-tauri-remote/src/host/utils/local.test.ts
diff --git a/packages/dsh-tauri-ssh/src/host/utils/local.ts b/packages/dsh-tauri-remote/src/host/utils/local.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/local.ts
rename to packages/dsh-tauri-remote/src/host/utils/local.ts
diff --git a/packages/dsh-tauri-remote/src/host/utils/migrate.test.ts b/packages/dsh-tauri-remote/src/host/utils/migrate.test.ts
new file mode 100644
index 00000000..68dcd055
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/utils/migrate.test.ts
@@ -0,0 +1,110 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'pathe'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { migrateDocument } from './migrate'
+
+const roots: string[] = []
+
+function scratch(): string {
+ const root = mkdtempSync(join(tmpdir(), 'dsh-remote-migrate-'))
+ roots.push(root)
+ return root
+}
+
+function write(file: string, document: unknown): void {
+ mkdirSync(dirname(file), { recursive: true })
+ writeFileSync(file, `${JSON.stringify(document, null, 2)}\n`)
+}
+
+beforeEach(() => {})
+
+afterEach(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
+})
+
+describe('migrateDocument', () => {
+ it('旧文件存在且新文件不存在时写出新文件并保留旧文件', () => {
+ const root = scratch()
+ const source = join(root, 'ssh', 'machines.json')
+ const target = join(root, 'remote', 'machines.json')
+ write(source, { version: 1, machines: { a: { id: 'a' } } })
+ expect(migrateDocument(source, target)).toBe(true)
+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ version: 1, machines: { a: { id: 'a' } } })
+ expect(existsSync(source)).toBe(true)
+ expect(statSync(target).mode & 0o777).toBe(0o600)
+ expect(statSync(dirname(target)).mode & 0o777).toBe(0o700)
+ })
+
+ it('新文件已存在时不迁移也不覆盖(含半迁移的空文件)', () => {
+ const root = scratch()
+ const source = join(root, 'ssh', 'machines.json')
+ const target = join(root, 'remote', 'machines.json')
+ write(source, { version: 1, machines: { legacy: { id: 'legacy' } } })
+ write(target, { version: 1, machines: { current: { id: 'current' } } })
+ expect(migrateDocument(source, target)).toBe(false)
+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ version: 1, machines: { current: { id: 'current' } } })
+
+ const empty = join(root, 'remote', 'known-hosts.json')
+ writeFileSync(empty, '')
+ write(join(root, 'ssh', 'known-hosts.json'), [{ machineId: 'a', fingerprint: 'SHA256:x' }])
+ expect(migrateDocument(join(root, 'ssh', 'known-hosts.json'), empty)).toBe(false)
+ expect(readFileSync(empty, 'utf8')).toBe('')
+ })
+
+ it('旧文件不存在时不做任何动作', () => {
+ const root = scratch()
+ expect(migrateDocument(join(root, 'ssh', 'machines.json'), join(root, 'remote', 'machines.json'))).toBe(false)
+ expect(existsSync(join(root, 'remote'))).toBe(false)
+ })
+
+ it('旧文件损坏时抛出可读原因且不产生目标文件', () => {
+ const root = scratch()
+ const source = join(root, 'ssh', 'machines.json')
+ const target = join(root, 'remote', 'machines.json')
+ mkdirSync(dirname(source), { recursive: true })
+ writeFileSync(source, '{ not json')
+ expect(() => migrateDocument(source, target)).toThrow(/不是合法 JSON/u)
+ expect(existsSync(target)).toBe(false)
+ expect(existsSync(source)).toBe(true)
+ })
+
+ it('损坏与不可读的原因只带文件名,不带 home 下的绝对路径', () => {
+ const root = scratch()
+ const corrupt = join(root, 'ssh', 'machines.json')
+ const unreadable = join(root, 'ssh', 'known-hosts.json')
+ mkdirSync(corrupt, { recursive: true })
+ mkdirSync(dirname(unreadable), { recursive: true })
+ writeFileSync(unreadable, '{ not json')
+
+ const reasonOf = (source: string, index: number): string => {
+ try {
+ migrateDocument(source, join(root, 'remote', `target-${index}.json`))
+ return ''
+ }
+ catch (error) {
+ return (error as Error).message
+ }
+ }
+
+ const reasons = [reasonOf(corrupt, 0), reasonOf(unreadable, 1)]
+
+ for (const reason of reasons) {
+ expect(reason).toContain('旧状态文件')
+ expect(reason).not.toContain(root)
+ }
+ expect(reasons[0]).toContain('machines.json')
+ expect(reasons[1]).toContain('known-hosts.json')
+ })
+
+ it('重复执行结果相同(第二次为空操作)', () => {
+ const root = scratch()
+ const source = join(root, 'ssh', 'machines.json')
+ const target = join(root, 'remote', 'machines.json')
+ write(source, { version: 1, machines: {} })
+ expect(migrateDocument(source, target)).toBe(true)
+ const migrated = readFileSync(target, 'utf8')
+ expect(migrateDocument(source, target)).toBe(false)
+ expect(readFileSync(target, 'utf8')).toBe(migrated)
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/host/utils/migrate.ts b/packages/dsh-tauri-remote/src/host/utils/migrate.ts
new file mode 100644
index 00000000..84d8cbbb
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/utils/migrate.ts
@@ -0,0 +1,48 @@
+import { randomBytes } from 'node:crypto'
+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { basename, dirname } from 'pathe'
+import { messageOf } from '../../shared/error'
+
+/** 报错只带文件名:这条原因经 `GET /settings` 下发到 web 载体,不下发 home 下的绝对路径。 */
+function readDocument(file: string): unknown {
+ const name = basename(file)
+ let raw: string
+ try {
+ raw = readFileSync(file, 'utf8')
+ }
+ catch (error) {
+ throw new Error(`旧状态文件不可读 ${name}:${messageOf(error)}`)
+ }
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(raw)
+ }
+ catch {
+ throw new Error(`旧状态文件不是合法 JSON ${name}`)
+ }
+ if (typeof parsed !== 'object' || parsed === null)
+ throw new Error(`旧状态文件不是 JSON 对象 ${name}`)
+ return parsed
+}
+
+/**
+ * 一次性迁移一份状态文档:目标已存在(含半迁移的空文件)或源不存在即不动作;旧文件保留原位。
+ *
+ * @returns 是否真的写出目标文件。
+ */
+export function migrateDocument(source: string, target: string): boolean {
+ if (existsSync(target) || !existsSync(source))
+ return false
+ const document = readDocument(source)
+ mkdirSync(dirname(target), { recursive: true, mode: 0o700 })
+ const temp = `${target}.${randomBytes(6).toString('hex')}.tmp`
+ try {
+ writeFileSync(temp, `${JSON.stringify(document, null, 2)}\n`, { mode: 0o600, flag: 'wx' })
+ renameSync(temp, target)
+ }
+ catch (error) {
+ rmSync(temp, { force: true })
+ throw error
+ }
+ return true
+}
diff --git a/packages/dsh-tauri-ssh/src/host/utils/packing.test.ts b/packages/dsh-tauri-remote/src/host/utils/packing.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/packing.test.ts
rename to packages/dsh-tauri-remote/src/host/utils/packing.test.ts
diff --git a/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.test.ts b/packages/dsh-tauri-remote/src/host/utils/plugins-sync.test.ts
similarity index 91%
rename from packages/dsh-tauri-ssh/src/host/utils/plugins-sync.test.ts
rename to packages/dsh-tauri-remote/src/host/utils/plugins-sync.test.ts
index 9e73053c..1f6aaa77 100644
--- a/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.test.ts
+++ b/packages/dsh-tauri-remote/src/host/utils/plugins-sync.test.ts
@@ -9,24 +9,24 @@ describe('findBundledPluginsTree', () => {
it('locates deployed plugins from the dev layout and excludes ordinary dependencies', () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-plugins-discovery-'))
try {
- const source = join(root, 'packages', 'dsh-tauri-ssh')
+ const source = join(root, 'packages', 'dsh-tauri-remote')
const deployed = join(root, 'src-tauri', 'resources', 'node_modules')
mkdirSync(source, { recursive: true })
- writeFileSync(join(source, 'package.json'), '{"name":"dsh-tauri-ssh"}')
- for (const name of ['dsh-tauri-ssh', 'dsh-tauri-ui', 'ssh2', 'dsh-tauri-panel']) {
+ writeFileSync(join(source, 'package.json'), '{"name":"dsh-tauri-remote"}')
+ for (const name of ['dsh-tauri-remote', 'dsh-tauri-ui', 'ssh2', 'dsh-tauri-panel']) {
mkdirSync(join(deployed, name), { recursive: true })
writeFileSync(join(deployed, name, 'package.json'), JSON.stringify({
name,
- ...name === 'dsh-tauri-ssh' || name === 'dsh-tauri-ui' ? { dsh: { bundle: {} } } : {},
+ ...name === 'dsh-tauri-remote' || name === 'dsh-tauri-ui' ? { dsh: { bundle: {} } } : {},
}))
}
expect(findBundledPluginsTree(source)).toEqual({
root: deployed,
- pluginNames: ['dsh-tauri-ssh', 'dsh-tauri-ui'],
+ pluginNames: ['dsh-tauri-remote', 'dsh-tauri-ui'],
})
- expect(findBundledPluginsTree(join(deployed, 'dsh-tauri-ssh'))).toEqual({
+ expect(findBundledPluginsTree(join(deployed, 'dsh-tauri-remote'))).toEqual({
root: deployed,
- pluginNames: ['dsh-tauri-ssh', 'dsh-tauri-ui'],
+ pluginNames: ['dsh-tauri-remote', 'dsh-tauri-ui'],
})
}
finally {
@@ -65,7 +65,7 @@ describe('buildPluginsBundle', () => {
})
describe('plugin sync commands', () => {
- const tree = { root: '/x', pluginNames: ['dsh-tauri', 'dsh-tauri-ssh'] }
+ const tree = { root: '/x', pluginNames: ['dsh-tauri', 'dsh-tauri-remote'] }
it('marker command reads the remote hash silently', () => {
expect(pluginSyncMarkerCommand()).toContain('.dsh-desktop/plugins/.sync-sha256')
@@ -81,7 +81,7 @@ describe('plugin sync commands', () => {
// profile 接线走上传的 _wire.js(deps link + bundles + symlink)
expect(command).toContain('_wire.js')
expect(command).toContain('.dsh/profiles/remote/package.json')
- expect(command).toContain('dsh-tauri dsh-tauri-ssh')
+ expect(command).toContain('dsh-tauri dsh-tauri-remote')
// 实例在跑则按 pidfile 重启(ensure 探测落空后按新 profile 拉起);
// pidfile 之外按安装路径精确清场,并等远端实例端口释放避免新实例 EADDRINUSE
expect(command).toContain('.dsh/dsh-remote.pid')
diff --git a/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.ts b/packages/dsh-tauri-remote/src/host/utils/plugins-sync.ts
similarity index 95%
rename from packages/dsh-tauri-ssh/src/host/utils/plugins-sync.ts
rename to packages/dsh-tauri-remote/src/host/utils/plugins-sync.ts
index 58a042ef..46810972 100644
--- a/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.ts
+++ b/packages/dsh-tauri-remote/src/host/utils/plugins-sync.ts
@@ -1,5 +1,5 @@
import type { Buffer } from 'node:buffer'
-import type { SshMachineStage, SshSession } from '../types/index'
+import type { RemoteMachineStage, RemoteSession } from '../types/index'
import { execFile } from 'node:child_process'
import { createHash } from 'node:crypto'
import { existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
@@ -57,7 +57,7 @@ export function findBundledPluginsTree(ownPkgDir = dirname(realpathSync(fileURLT
for (let depth = 0; depth < 6; depth += 1) {
try {
const manifest = JSON.parse(readFileSync(join(ownPkgDir, 'package.json'), 'utf8')) as { name?: string }
- if (manifest.name === 'dsh-tauri-ssh')
+ if (manifest.name === 'dsh-tauri-remote')
break
}
catch { /* 继续上溯 */ }
@@ -68,7 +68,7 @@ export function findBundledPluginsTree(ownPkgDir = dirname(realpathSync(fileURLT
resolve(ownPkgDir, '../../src-tauri/resources/node_modules'),
]
for (const root of candidates) {
- if (!existsSync(join(root, 'dsh-tauri-ssh', 'package.json'))
+ if (!existsSync(join(root, 'dsh-tauri-remote', 'package.json'))
|| !existsSync(join(root, 'ssh2', 'package.json'))) {
continue
}
@@ -135,10 +135,10 @@ export function pluginSyncApplyCommand(tree: BundledPluginsTree, hash: string, p
}
export async function syncBundledPlugins(
- session: SshSession,
+ session: RemoteSession,
profileName: string,
remotePort: number,
- hooks: { onEvent?: (stage: SshMachineStage, line: string) => void, tree?: BundledPluginsTree | undefined } = {},
+ hooks: { onEvent?: (stage: RemoteMachineStage, line: string) => void, tree?: BundledPluginsTree | undefined } = {},
): Promise<boolean> {
const tree = hooks.tree ?? findBundledPluginsTree()
if (tree === undefined) {
diff --git a/packages/dsh-tauri-ssh/src/host/utils/shell.ts b/packages/dsh-tauri-remote/src/host/utils/shell.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/shell.ts
rename to packages/dsh-tauri-remote/src/host/utils/shell.ts
diff --git a/packages/dsh-tauri-remote/src/host/utils/source.test.ts b/packages/dsh-tauri-remote/src/host/utils/source.test.ts
new file mode 100644
index 00000000..ac052db9
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/utils/source.test.ts
@@ -0,0 +1,248 @@
+import type { IncomingHttpHeaders } from 'node:http'
+import type { RemoteAccessDecision, RemoteAuthPolicy, RemotePasswordRecord, RemoteSourceClass } from '../types/index'
+import { describe, expect, it } from 'vitest'
+import { classifyPeer, classifySource, decideSourceAccess, isAuthConfigured, isAuthStorageBroken, isIpAddress, isLoopbackPeer, isLoopbackSource, rateLimitKeyOf } from './source'
+
+const SESSION = 'session-token'
+
+const PASSWORD: RemotePasswordRecord = { algo: 'pbkdf2-sha256', salt: 'c2FsdA==', iterations: 1, hash: 'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=' }
+
+const CORRUPT_PASSWORD: RemotePasswordRecord = { ...PASSWORD, hash: 'aGFzaA==' }
+
+const NO_AUTH: undefined = undefined
+
+const PUBLIC_ONLY: RemoteAuthPolicy = { enabled: true, scope: 'public_only', password: PASSWORD, linkToken: null, sessionSecret: SESSION }
+
+const ALL_SOURCES: RemoteAuthPolicy = { ...PUBLIC_ONLY, scope: 'all' }
+
+function headers(source?: string | string[], session?: string | string[]): IncomingHttpHeaders {
+ return {
+ ...source === undefined ? {} : { 'x-dsh-remote-source': source },
+ ...session === undefined ? {} : { 'x-dsh-remote-session': session },
+ }
+}
+
+describe('classifyPeer', () => {
+ it.each(['127.0.0.1', '127.0.0.2', '127.255.255.254', '::1', '::ffff:127.0.0.1', '::ffff:127.9.9.9'])('classifies %s as loopback', (address) => {
+ expect(classifyPeer(address)).toBe('loopback')
+ })
+
+ it.each([
+ '10.1.2.3',
+ '172.16.0.1',
+ '172.31.255.255',
+ '192.168.1.20',
+ '169.254.3.4',
+ '100.64.0.1',
+ '100.127.255.254',
+ '::ffff:192.168.1.5',
+ 'fe80::1',
+ 'fe80::1%en0',
+ 'fc00::1',
+ 'fd12:3456::1',
+ ])('classifies %s as private', (address) => {
+ expect(classifyPeer(address)).toBe('private')
+ })
+
+ it.each([
+ '8.8.8.8',
+ '172.15.0.1',
+ '172.32.0.1',
+ '192.169.1.1',
+ '169.255.1.1',
+ '100.63.0.1',
+ '100.128.0.1',
+ '2606:4700:4700::1111',
+ '::',
+ 'not-an-ip',
+ '10.1.2',
+ '10.1.2.999',
+ '',
+ undefined,
+ ])('classifies %s as public', (address) => {
+ expect(classifyPeer(address)).toBe('public')
+ })
+})
+
+describe('isLoopbackPeer', () => {
+ it.each(['127.0.0.1', '127.0.0.2', '::1', '::ffff:127.0.0.1'])('accepts %s as the loopback peer', (address) => {
+ expect(isLoopbackPeer(address)).toBe(true)
+ })
+
+ it.each(['10.1.2.3', '192.168.1.20', '::ffff:10.1.2.3', undefined, ''])('rejects %s as a non-loopback peer', (address) => {
+ expect(isLoopbackPeer(address)).toBe(false)
+ })
+})
+
+describe('isIpAddress', () => {
+ it.each(['127.0.0.1', '192.168.1.5', '203.0.113.9', '::1', 'fd00::1'])('accepts the address literal %s', (address) => {
+ expect(isIpAddress(address)).toBe(true)
+ })
+
+ it.each(['', 'localhost', '1.2.3', '999.1.1.1', '1.2.3.4.5', undefined])('rejects the non-address %s', (address) => {
+ expect(isIpAddress(address)).toBe(false)
+ })
+})
+
+describe('classifySource', () => {
+ /**
+ * 「两枚头都不存在 → 回退 TCP 对端」是 S2 §9 明文规定的插件侧判定(主 Spec §5 把该机制的
+ * 定义权判给 S2)。它同时是桌面壳经 Tauri 桥直连回环的唯一放行依据,故不能收紧成一律拒绝;
+ * 网关反代到本机 DSH 时对端也是回环,S2 注入腿一旦漏注入,本插件看到的正是这一形态,
+ * 防线在 S2 侧(先剥离后必注入),不在本函数。
+ */
+ it('falls back to the peer address when neither internal header is present', () => {
+ expect(classifySource(headers(), '127.0.0.1', SESSION)).toBe('loopback')
+ expect(classifySource(headers(), '10.1.2.3', SESSION)).toBe('private')
+ expect(classifySource(headers(), '8.8.8.8', SESSION)).toBe('public')
+ })
+
+ it('adopts the declared classification of a forwarded request whose session matches', () => {
+ expect(classifySource(headers('loopback', SESSION), '10.1.2.3', SESSION)).toBe('loopback')
+ expect(classifySource(headers('private', SESSION), '127.0.0.1', SESSION)).toBe('private')
+ expect(classifySource(headers('public', SESSION), '127.0.0.1', SESSION)).toBe('public')
+ expect(classifySource(headers('tunnel', SESSION), '127.0.0.1', SESSION)).toBe('tunnel')
+ })
+
+ it('rejects a classified request whose session token does not match', () => {
+ expect(classifySource(headers('loopback', 'forged'), '127.0.0.1', SESSION)).toBe('public')
+ expect(classifySource(headers('tunnel', 'forged'), '127.0.0.1', SESSION)).toBe('public')
+ })
+
+ it('rejects a classification header without the session header even from a loopback peer', () => {
+ expect(classifySource(headers('loopback'), '127.0.0.1', SESSION)).toBe('public')
+ expect(classifySource(headers(undefined, SESSION), '127.0.0.1', SESSION)).toBe('public')
+ })
+
+ it('rejects every classified request while no gateway session is installed', () => {
+ expect(classifySource(headers('loopback', SESSION), '127.0.0.1', '')).toBe('public')
+ })
+
+ it('rejects a duplicated multi-value classification header', () => {
+ expect(classifySource(headers(['private', 'loopback'], SESSION), '127.0.0.1', SESSION)).toBe('public')
+ expect(classifySource(headers('loopback', [SESSION, SESSION]), '127.0.0.1', SESSION)).toBe('public')
+ })
+
+ it.each(['private, loopback', 'private, loopback, tunnel'])('rejects the comma-joined %j that a gateway append produces', (joined) => {
+ expect(classifySource(headers(joined, SESSION), '127.0.0.1', SESSION)).toBe('public')
+ expect(classifySource(headers(joined, SESSION), '10.1.2.3', SESSION)).toBe('public')
+ })
+
+ it.each(['loopback ', 'LOOPBACK', 'lan', ''])('rejects the unknown classification %j instead of trusting it', (declared) => {
+ expect(classifySource(headers(declared, SESSION), '127.0.0.1', SESSION)).toBe('public')
+ })
+
+ it('never falls back to the peer address once any internal header is present', () => {
+ expect(classifySource(headers('loopback', 'stale'), '127.0.0.1', SESSION)).toBe('public')
+ expect(classifySource(headers(undefined, 'stale'), '127.0.0.1', SESSION)).toBe('public')
+ })
+
+ it('ignores the spoofable forwarding headers entirely', () => {
+ const spoofed: IncomingHttpHeaders = { 'x-forwarded-for': '127.0.0.1', 'cf-connecting-ip': '127.0.0.1' }
+ expect(classifySource(spoofed, '203.0.113.9', SESSION)).toBe('public')
+ expect(classifySource(spoofed, '10.0.0.9', SESSION)).toBe('private')
+ })
+})
+
+describe('isLoopbackSource', () => {
+ it('is exactly the loopback classification, forwarded or direct', () => {
+ expect(isLoopbackSource(headers(), '127.0.0.1', SESSION)).toBe(true)
+ expect(isLoopbackSource(headers('loopback', SESSION), '10.1.2.3', SESSION)).toBe(true)
+ expect(isLoopbackSource(headers('tunnel', SESSION), '127.0.0.1', SESSION)).toBe(false)
+ expect(isLoopbackSource(headers(), '10.1.2.3', SESSION)).toBe(false)
+ })
+})
+
+describe('isAuthConfigured', () => {
+ it('requires the switch plus at least one credential', () => {
+ expect(isAuthConfigured(NO_AUTH)).toBe(false)
+ expect(isAuthConfigured({ ...PUBLIC_ONLY, enabled: false })).toBe(false)
+ expect(isAuthConfigured({ ...PUBLIC_ONLY, password: null, linkToken: null })).toBe(false)
+ expect(isAuthConfigured({ ...PUBLIC_ONLY, password: null, linkToken: '' })).toBe(false)
+ expect(isAuthConfigured(PUBLIC_ONLY)).toBe(true)
+ expect(isAuthConfigured({ ...PUBLIC_ONLY, password: null, linkToken: 'token' })).toBe(true)
+ })
+
+ it('treats a corrupted password record without a link token as unconfigured', () => {
+ expect(isAuthConfigured({ ...PUBLIC_ONLY, password: CORRUPT_PASSWORD })).toBe(false)
+ expect(isAuthConfigured({ ...PUBLIC_ONLY, password: CORRUPT_PASSWORD, linkToken: 'token' })).toBe(true)
+ })
+})
+
+describe('isAuthStorageBroken', () => {
+ it('reports corruption only while no usable credential remains', () => {
+ expect(isAuthStorageBroken(NO_AUTH)).toBe(false)
+ expect(isAuthStorageBroken(PUBLIC_ONLY)).toBe(false)
+ expect(isAuthStorageBroken({ ...PUBLIC_ONLY, password: null, linkToken: null })).toBe(false)
+ expect(isAuthStorageBroken({ ...PUBLIC_ONLY, password: CORRUPT_PASSWORD })).toBe(true)
+ expect(isAuthStorageBroken({ ...PUBLIC_ONLY, password: CORRUPT_PASSWORD, linkToken: 'token' })).toBe(false)
+ expect(isAuthStorageBroken({ ...PUBLIC_ONLY, password: CORRUPT_PASSWORD, enabled: false })).toBe(false)
+ })
+})
+
+describe('decideSourceAccess', () => {
+ const SOURCES: RemoteSourceClass[] = ['loopback', 'private', 'public', 'tunnel']
+
+ const CASES: ReadonlyArray<{ source: RemoteSourceClass, unconfigured: RemoteAccessDecision, publicOnly: RemoteAccessDecision, all: RemoteAccessDecision }> = [
+ { source: 'loopback', unconfigured: 'allow', publicOnly: 'allow', all: 'allow' },
+ { source: 'private', unconfigured: 'allow', publicOnly: 'allow', all: 'authenticate' },
+ { source: 'public', unconfigured: 'deny', publicOnly: 'authenticate', all: 'authenticate' },
+ { source: 'tunnel', unconfigured: 'deny', publicOnly: 'authenticate', all: 'authenticate' },
+ ]
+
+ it('covers every source of the four-by-three matrix', () => {
+ expect(CASES.map(entry => entry.source)).toEqual(SOURCES)
+ })
+
+ for (const entry of CASES) {
+ it(`【矩阵】${entry.source} × 未配置认证 判定为 ${entry.unconfigured}`, () => {
+ expect(decideSourceAccess(entry.source, NO_AUTH)).toBe(entry.unconfigured)
+ })
+
+ it(`【矩阵】${entry.source} × scope=public_only 判定为 ${entry.publicOnly}`, () => {
+ expect(decideSourceAccess(entry.source, PUBLIC_ONLY)).toBe(entry.publicOnly)
+ })
+
+ it(`【矩阵】${entry.source} × scope=all 判定为 ${entry.all}`, () => {
+ expect(decideSourceAccess(entry.source, ALL_SOURCES)).toBe(entry.all)
+ })
+ }
+
+ it('treats an enabled switch without any credential as unconfigured', () => {
+ const halfOpen: RemoteAuthPolicy = { ...PUBLIC_ONLY, password: null, linkToken: null }
+ expect(decideSourceAccess('public', halfOpen)).toBe('deny')
+ expect(decideSourceAccess('private', halfOpen)).toBe('allow')
+ })
+
+ it('treats a corrupted password record without a link token as unconfigured', () => {
+ const corrupted: RemoteAuthPolicy = { ...PUBLIC_ONLY, password: CORRUPT_PASSWORD }
+ expect(decideSourceAccess('public', corrupted)).toBe('deny')
+ expect(decideSourceAccess('tunnel', corrupted)).toBe('deny')
+ expect(decideSourceAccess('private', corrupted)).toBe('allow')
+ expect(decideSourceAccess('loopback', corrupted)).toBe('allow')
+ })
+
+ it('keeps the physical loopback source free of authentication in every configuration', () => {
+ expect(decideSourceAccess('loopback', ALL_SOURCES)).toBe('allow')
+ expect(decideSourceAccess('loopback', { ...ALL_SOURCES, password: null, linkToken: null })).toBe('allow')
+ })
+})
+
+describe('rateLimitKeyOf', () => {
+ it('uses the tunnel-declared client address for tunnel sources only', () => {
+ expect(rateLimitKeyOf('tunnel', '127.0.0.1', '203.0.113.7')).toBe('203.0.113.7')
+ expect(rateLimitKeyOf('tunnel', '127.0.0.1', '2001:db8::7')).toBe('2001:db8::7')
+ })
+
+ it('ignores the declared address for every other source', () => {
+ expect(rateLimitKeyOf('private', '192.168.1.5', '203.0.113.7')).toBe('192.168.1.5')
+ expect(rateLimitKeyOf('public', '198.51.100.9', '203.0.113.7')).toBe('198.51.100.9')
+ expect(rateLimitKeyOf('loopback', '127.0.0.1', '203.0.113.7')).toBe('127.0.0.1')
+ })
+
+ it('falls back to the peer address when the declared address is missing or malformed', () => {
+ expect(rateLimitKeyOf('tunnel', '127.0.0.1', undefined)).toBe('127.0.0.1')
+ expect(rateLimitKeyOf('tunnel', '127.0.0.1', 'not-an-ip')).toBe('127.0.0.1')
+ expect(rateLimitKeyOf('tunnel', undefined, undefined)).toBe('unknown')
+ })
+})
diff --git a/packages/dsh-tauri-remote/src/host/utils/source.ts b/packages/dsh-tauri-remote/src/host/utils/source.ts
new file mode 100644
index 00000000..9205bbc8
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/host/utils/source.ts
@@ -0,0 +1,135 @@
+import type { IncomingHttpHeaders } from 'node:http'
+import type { RemoteAccessDecision, RemoteAuthPolicy, RemoteSourceClass } from '../types/index'
+import { Buffer } from 'node:buffer'
+import { timingSafeEqual } from 'node:crypto'
+import { GATEWAY_SESSION_HEADER, GATEWAY_SOURCE_HEADER } from '../config/constants'
+import { isPasswordRecordUsable } from './auth'
+
+export type PeerSourceClass = Exclude<RemoteSourceClass, 'tunnel'>
+
+const SOURCE_CLASSES: readonly RemoteSourceClass[] = ['loopback', 'private', 'public', 'tunnel']
+
+/** TCP 对端地址分类(S2 §7.1):127/8 与 ::1 回环;10/8、172.16/12、192.168/16、169.254/16、100.64/10 与 fc00::/7、fe80::/10 私网;其余公网。 */
+export function classifyPeer(address: string | undefined): PeerSourceClass {
+ const host = mappedHost(address)
+ if (host === '')
+ return 'public'
+ return host.includes(':') ? classifyIpv6(host) : classifyIpv4(host)
+}
+
+export function isLoopbackPeer(address: string | undefined): boolean {
+ return classifyPeer(address) === 'loopback'
+}
+
+/**
+ * 来源分类判定:两枚内部标识头都不存在时回退 TCP 对端地址;任一枚存在则必须两枚同时有效
+ * (单值 + 会话标识匹配 + 取值合法)才采用其声明,否则一律按不可信处理——网关转发到本机 DSH
+ * 时对端恒为回环,回退会把伪造头变成回环权限。转发头(X-Forwarded-For 等)不参与判定。
+ */
+export function classifySource(headers: IncomingHttpHeaders, peerAddress: string | undefined, session: string): RemoteSourceClass {
+ const declared = headers[GATEWAY_SOURCE_HEADER]
+ const token = headers[GATEWAY_SESSION_HEADER]
+ if (declared === undefined && token === undefined)
+ return classifyPeer(peerAddress)
+ if (typeof declared !== 'string' || typeof token !== 'string')
+ return 'public'
+ if (session === '' || !sessionMatches(token, session))
+ return 'public'
+ return isSourceClass(declared) ? declared : 'public'
+}
+
+export function isLoopbackSource(headers: IncomingHttpHeaders, peerAddress: string | undefined, session: string): boolean {
+ return classifySource(headers, peerAddress, session) === 'loopback'
+}
+
+/** 认证配置是否成立:启用且至少存在一种**可用**凭据(未损坏的密码记录或非空链接 Token),否则等同未配置(S2 §7.4/§11)。 */
+export function isAuthConfigured(policy: RemoteAuthPolicy | undefined): policy is RemoteAuthPolicy {
+ if (policy === undefined || !policy.enabled)
+ return false
+ return isPasswordRecordUsable(policy.password) || (policy.linkToken !== null && policy.linkToken !== '')
+}
+
+/** 凭据存在但不可用(密码记录损坏且无链接 Token)→ 引导「重新设置密码」而不是空白的未配置拒绝(S2 §11)。 */
+export function isAuthStorageBroken(policy: RemoteAuthPolicy | undefined): boolean {
+ return policy !== undefined && policy.enabled && policy.password !== null && !isAuthConfigured(policy)
+}
+
+/** 判定矩阵(S2 §7.2):回环恒放行,不提供 lan_only 档位。 */
+export function decideSourceAccess(source: RemoteSourceClass, policy: RemoteAuthPolicy | undefined): RemoteAccessDecision {
+ if (source === 'loopback')
+ return 'allow'
+ if (!isAuthConfigured(policy))
+ return source === 'private' ? 'allow' : 'deny'
+ if (source === 'private' && policy.scope === 'public_only')
+ return 'allow'
+ return 'authenticate'
+}
+
+/** 限速分桶键:仅隧道来源(内部标识可信)允许采用隧道侧声明的客户端 IP,且只影响分桶(S2 §7.1/§7.4)。 */
+export function rateLimitKeyOf(source: RemoteSourceClass, peerAddress: string | undefined, declaredClientIp: string | undefined): string {
+ if (source === 'tunnel' && isIpAddress(declaredClientIp))
+ return declaredClientIp
+ return peerAddress === undefined || peerAddress === '' ? 'unknown' : peerAddress
+}
+
+export function isIpAddress(value: string | undefined): value is string {
+ if (value === undefined || value === '')
+ return false
+ const host = mappedHost(value)
+ return host.includes(':') ? /^[0-9a-f:]+$/i.test(host) : classifyIpv4Shape(host)
+}
+
+// --- internal ---
+function mappedHost(address: string | undefined): string {
+ if (address === undefined)
+ return ''
+ const withoutZone = address.split('%')[0] ?? ''
+ return /^::ffff:/i.test(withoutZone) ? withoutZone.slice(7) : withoutZone
+}
+
+function classifyIpv4(host: string): PeerSourceClass {
+ const octets = host.split('.').map(octetOf)
+ const [first, second] = octets
+ if (octets.length !== 4 || first === undefined || second === undefined || octets.includes(undefined))
+ return 'public'
+ if (first === 127)
+ return 'loopback'
+ if (first === 10 || (first === 192 && second === 168) || (first === 169 && second === 254))
+ return 'private'
+ if (first === 172 && second >= 16 && second <= 31)
+ return 'private'
+ if (first === 100 && second >= 64 && second <= 127)
+ return 'private'
+ return 'public'
+}
+
+function classifyIpv6(host: string): PeerSourceClass {
+ const lower = host.toLowerCase()
+ if (lower === '::1')
+ return 'loopback'
+ if (/^f[cd]/.test(lower) || /^fe[89ab]/.test(lower))
+ return 'private'
+ return 'public'
+}
+
+function classifyIpv4Shape(host: string): boolean {
+ const octets = host.split('.').map(octetOf)
+ return octets.length === 4 && octets.every(octet => octet !== undefined)
+}
+
+function octetOf(value: string | undefined): number | undefined {
+ if (value === undefined || !/^\d{1,3}$/.test(value))
+ return undefined
+ const parsed = Number(value)
+ return parsed <= 255 ? parsed : undefined
+}
+
+function isSourceClass(value: string): value is RemoteSourceClass {
+ return (SOURCE_CLASSES as readonly string[]).includes(value)
+}
+
+function sessionMatches(token: string, session: string): boolean {
+ const left = Buffer.from(token)
+ const right = Buffer.from(session)
+ return left.length === right.length && timingSafeEqual(left, right)
+}
diff --git a/packages/dsh-tauri-ssh/src/host/utils/ssh-config.test.ts b/packages/dsh-tauri-remote/src/host/utils/ssh-config.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/ssh-config.test.ts
rename to packages/dsh-tauri-remote/src/host/utils/ssh-config.test.ts
diff --git a/packages/dsh-tauri-ssh/src/host/utils/ssh-config.ts b/packages/dsh-tauri-remote/src/host/utils/ssh-config.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/ssh-config.ts
rename to packages/dsh-tauri-remote/src/host/utils/ssh-config.ts
diff --git a/packages/dsh-tauri-ssh/src/host/utils/version.test.ts b/packages/dsh-tauri-remote/src/host/utils/version.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/utils/version.test.ts
rename to packages/dsh-tauri-remote/src/host/utils/version.test.ts
diff --git a/packages/dsh-tauri-ssh/src/host/utils/version.ts b/packages/dsh-tauri-remote/src/host/utils/version.ts
similarity index 99%
rename from packages/dsh-tauri-ssh/src/host/utils/version.ts
rename to packages/dsh-tauri-remote/src/host/utils/version.ts
index 160c260d..f8247ed8 100644
--- a/packages/dsh-tauri-ssh/src/host/utils/version.ts
+++ b/packages/dsh-tauri-remote/src/host/utils/version.ts
@@ -127,7 +127,7 @@ async function fetchJson(url: string, headers: Record<string, string>, timeoutMs
export async function listGithubReleases(repo: string, timeoutMs = 15_000): Promise<DshPkgReleaseMeta[]> {
const json = await fetchJson(
`https://api.github.com/repos/${repo}/releases?per_page=100`,
- { 'accept': 'application/vnd.github+json', 'user-agent': 'dsh-tauri-ssh' },
+ { 'accept': 'application/vnd.github+json', 'user-agent': 'dsh-tauri-remote' },
timeoutMs,
)
if (!Array.isArray(json))
@@ -142,7 +142,7 @@ export async function listGithubReleases(repo: string, timeoutMs = 15_000): Prom
export async function listGithubAssets(repo: string, tag: string, timeoutMs = 15_000): Promise<GithubAsset[]> {
const json = await fetchJson(
`https://api.github.com/repos/${repo}/releases/tags/${encodeURIComponent(tag)}`,
- { 'accept': 'application/vnd.github+json', 'user-agent': 'dsh-tauri-ssh' },
+ { 'accept': 'application/vnd.github+json', 'user-agent': 'dsh-tauri-remote' },
timeoutMs,
)
const assets = (json as { assets?: unknown }).assets
diff --git a/packages/dsh-tauri-remote/src/index.ts b/packages/dsh-tauri-remote/src/index.ts
new file mode 100644
index 00000000..8820ad73
--- /dev/null
+++ b/packages/dsh-tauri-remote/src/index.ts
@@ -0,0 +1,3 @@
+export { apply, Config, default, inject, name } from './host/apply'
+export { setSourceSession, sourceSessionToken } from './host/config/runtime'
+export type { RemoteMachineEvent, RemoteMachineEventsPage, RemoteMachineStage, RemoteMachineTerminal } from './host/types/index'
diff --git a/packages/dsh-tauri-ssh/src/shared/constants.test.ts b/packages/dsh-tauri-remote/src/shared/constants.test.ts
similarity index 59%
rename from packages/dsh-tauri-ssh/src/shared/constants.test.ts
rename to packages/dsh-tauri-remote/src/shared/constants.test.ts
index 27f1a736..793c5b58 100644
--- a/packages/dsh-tauri-ssh/src/shared/constants.test.ts
+++ b/packages/dsh-tauri-remote/src/shared/constants.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { DEFAULT_REMOTE_PROFILE } from '../host/config/constants'
+import { DEFAULT_MACHINE_TRANSPORT, DEFAULT_REMOTE_PROFILE } from '../host/config/constants'
import { machineProfileOf } from '../host/service/state.utils'
import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT, DEFAULT_REMOTE_PORT as hostRemotePort, DEFAULT_SSH_PORT as hostSshPort } from './constants'
@@ -21,4 +21,18 @@ describe('shared SSH defaults', () => {
const wire = { id: 'a', name: 'alpha', host: 'localhost', user: 'ops', port: 2222, remotePort: 4000 }
expect(machineProfileOf(wire)).toMatchObject({ port: 2222, remotePort: 4000 })
})
+
+ it('defaults the machine transport to ssh', () => {
+ expect(DEFAULT_MACHINE_TRANSPORT).toBe('ssh')
+ })
+
+ it('accepts a stored ssh transport without keeping the field on the profile', () => {
+ const profile = machineProfileOf({ id: 'a', name: 'alpha', host: 'localhost', user: 'ops', transport: 'ssh' })
+ expect(profile).toMatchObject({ id: 'a', name: 'alpha', host: 'localhost', user: 'ops' })
+ expect(profile).not.toHaveProperty('transport')
+ })
+
+ it('rejects a stored machine whose transport is unknown', () => {
+ expect(machineProfileOf({ id: 'a', name: 'alpha', host: 'localhost', user: 'ops', transport: 'telnet' })).toBeUndefined()
+ })
})
diff --git a/packages/dsh-tauri-ssh/src/shared/constants.ts b/packages/dsh-tauri-remote/src/shared/constants.ts
similarity index 59%
rename from packages/dsh-tauri-ssh/src/shared/constants.ts
rename to packages/dsh-tauri-remote/src/shared/constants.ts
index 9717c45c..307f332c 100644
--- a/packages/dsh-tauri-ssh/src/shared/constants.ts
+++ b/packages/dsh-tauri-remote/src/shared/constants.ts
@@ -1,4 +1,4 @@
-export const SSH_PLUGIN_NAME = 'dsh-tauri-ssh'
+export const REMOTE_PLUGIN_NAME = 'dsh-tauri-remote'
export const DEFAULT_SSH_PORT = 22
diff --git a/packages/dsh-tauri-ssh/src/shared/error.test.ts b/packages/dsh-tauri-remote/src/shared/error.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/shared/error.test.ts
rename to packages/dsh-tauri-remote/src/shared/error.test.ts
diff --git a/packages/dsh-tauri-ssh/src/shared/error.ts b/packages/dsh-tauri-remote/src/shared/error.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/shared/error.ts
rename to packages/dsh-tauri-remote/src/shared/error.ts
diff --git a/packages/dsh-tauri-ssh/tsconfig.json b/packages/dsh-tauri-remote/tsconfig.json
similarity index 100%
rename from packages/dsh-tauri-ssh/tsconfig.json
rename to packages/dsh-tauri-remote/tsconfig.json
diff --git a/packages/dsh-tauri-remote/tsdown.config.ts b/packages/dsh-tauri-remote/tsdown.config.ts
new file mode 100644
index 00000000..58e71305
--- /dev/null
+++ b/packages/dsh-tauri-remote/tsdown.config.ts
@@ -0,0 +1,15 @@
+import { defineDshConfig } from '../dsh-tauri-tsdown/src/index.ts'
+import { gatewayAuthHtml } from './src/host/service/gateway.auth.ts'
+
+// Host half (src/index.ts) + browser client bundle (src/client/index.ts)
+// wrapped in the dsh-client-modules closure factory.
+// qrcode 只在宿主侧生成二维码:构建期内联,部署树不带 pngjs(其 browserify 产物会让
+// 部署闭包校验误判相对引用缺失);因此它声明为 devDependency 而不是 dependencies。
+export default async function () {
+ return defineDshConfig({
+ server: {
+ noExternal: ['qrcode'],
+ define: { __GATEWAY_AUTH_HTML__: JSON.stringify(await gatewayAuthHtml()) },
+ },
+ })
+}
diff --git a/packages/dsh-tauri-ssh/cordis.patch.yml b/packages/dsh-tauri-ssh/cordis.patch.yml
deleted file mode 100644
index 23b14aa5..00000000
--- a/packages/dsh-tauri-ssh/cordis.patch.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-- insert:
- - id: ssh-remote
- name: dsh-tauri-ssh
diff --git a/packages/dsh-tauri-ssh/src/client/apis/index.ts b/packages/dsh-tauri-ssh/src/client/apis/index.ts
deleted file mode 100644
index e070b2a8..00000000
--- a/packages/dsh-tauri-ssh/src/client/apis/index.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * @title index
- * @swagger 2.0
- * @version 0.0.0
- */
-
-import type * as Types from "./index.type";
-import { ofetch } from "dsh-tauri/client";
-import type { FetchOptions } from "dsh-tauri/client";
-
-/** @method get */
-export function getSettings(options?: FetchOptions) {
- return ofetch<Types.GetApiTauriSshSettingsResponse>("/api/tauri/ssh/settings", { method: "get", ...options });
-}
-
-/** @method post */
-export function postSettings(body: Types.PostApiTauriSshSettingsBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshSettingsResponse>("/api/tauri/ssh/settings", { method: "post", body, ...options });
-}
-
-/** @method get */
-export function getSessionRole(options?: FetchOptions) {
- return ofetch<Types.GetApiTauriSshSessionRoleResponse>("/api/tauri/ssh/session/role", { method: "get", ...options });
-}
-
-/** @method get */
-export function getMachines(options?: FetchOptions) {
- return ofetch<Types.GetApiTauriSshMachinesResponse>("/api/tauri/ssh/machines", { method: "get", ...options });
-}
-
-/** @method post */
-export function postMachines(body: Types.PostApiTauriSshMachinesBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshMachinesResponse>("/api/tauri/ssh/machines", { method: "post", body, ...options });
-}
-
-/** @method delete */
-export function deleteMachines(body: Types.DeleteApiTauriSshMachinesBody, options?: FetchOptions) {
- return ofetch<Types.DeleteApiTauriSshMachinesResponse>("/api/tauri/ssh/machines", { method: "delete", body, ...options });
-}
-
-/** @method post */
-export function postMachinesTest(body: Types.PostApiTauriSshMachinesTestBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshMachinesTestResponse>("/api/tauri/ssh/machines/test", { method: "post", body, ...options });
-}
-
-/** @method post */
-export function postMachinesConnect(body: Types.PostApiTauriSshMachinesConnectBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshMachinesConnectResponse>("/api/tauri/ssh/machines/connect", { method: "post", body, ...options });
-}
-
-/** @method post */
-export function postMachinesDisconnect(body: Types.PostApiTauriSshMachinesDisconnectBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshMachinesDisconnectResponse>("/api/tauri/ssh/machines/disconnect", { method: "post", body, ...options });
-}
-
-/** @method post */
-export function postMachinesInstall(body: Types.PostApiTauriSshMachinesInstallBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshMachinesInstallResponse>("/api/tauri/ssh/machines/install", { method: "post", body, ...options });
-}
-
-/** @method get */
-export function getMachinesEvents(params?: Types.GetApiTauriSshMachinesEventsQuery, options?: FetchOptions) {
- return ofetch<Types.GetApiTauriSshMachinesEventsResponse>("/api/tauri/ssh/machines/events", { method: "get", params, ...options });
-}
-
-/** @method get */
-export function getSyncPreview(options?: FetchOptions) {
- return ofetch<Types.GetApiTauriSshSyncPreviewResponse>("/api/tauri/ssh/sync/preview", { method: "get", ...options });
-}
-
-/** @method post */
-export function postSyncApply(body: Types.PostApiTauriSshSyncApplyBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshSyncApplyResponse>("/api/tauri/ssh/sync/apply", { method: "post", body, ...options });
-}
diff --git a/packages/dsh-tauri-ssh/src/client/apis/index.type.ts b/packages/dsh-tauri-ssh/src/client/apis/index.type.ts
deleted file mode 100644
index 6c01b8a0..00000000
--- a/packages/dsh-tauri-ssh/src/client/apis/index.type.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-export type GetApiTauriSshSettingsResponse = { enabled?: false | true; error?: string };
-export type PostApiTauriSshSettingsResponse = { enabled?: false | true; error?: string };
-export type GetApiTauriSshSessionRoleResponse = { role?: string; remote?: false | true; origin?: string; error?: string };
-export type GetApiTauriSshMachinesResponse = {
- enabled?: false | true;
- items?: { id?: string; name?: string; host?: string; port?: number; user?: string; hasPassword?: false | true; hasPassphrase?: false | true; remotePort?: number; profileName?: string; startCommand?: string; color?: string; tintBorder?: false | true; state?: "disconnected" | "testing" | "connecting" | "connected" | "reconnecting" | "given-up"; tunnelBaseUrl?: string; lastError?: string; dshMissing?: false | true; progress?: { phase: "handshake" | "starting" | "probing" | "installing" | "syncing"; attempt?: number; total?: number; item?: string; log?: string }; nextRetryAt?: number; authMethod?: "agent" | "key" | "password" }[];
- discovered?: { id?: string; name?: string; host?: string; port?: number; user?: string; hasPassword?: false | true; hasPassphrase?: false | true; remotePort?: number; profileName?: string; startCommand?: string; color?: string; tintBorder?: false | true; state?: "disconnected" | "testing" | "connecting" | "connected" | "reconnecting" | "given-up"; tunnelBaseUrl?: string; lastError?: string; dshMissing?: false | true; progress?: { phase: "handshake" | "starting" | "probing" | "installing" | "syncing"; attempt?: number; total?: number; item?: string; log?: string }; nextRetryAt?: number; authMethod?: "agent" | "key" | "password" }[];
- error?: string;
-};
-export type PostApiTauriSshMachinesResponse = { error?: string };
-export type DeleteApiTauriSshMachinesResponse = { error?: string };
-export type PostApiTauriSshMachinesTestResponse = { ok?: false | true; banner?: string; message?: string; error?: string };
-export type PostApiTauriSshMachinesConnectResponse = { tunnelBaseUrl?: string; error?: string };
-export type PostApiTauriSshMachinesDisconnectResponse = { error?: string };
-export type PostApiTauriSshMachinesInstallResponse = { installed?: string[]; dshRef?: string; dshVersion?: string; dshPath?: string; credentialsCopied?: false | true; credentialsError?: string; error?: string };
-export type GetApiTauriSshMachinesEventsResponse = { items?: { seq?: number; ts?: string; machineId?: string; stage?: string; line?: string; terminal?: string; reason?: string }[]; nextSeq?: number; error?: string };
-export type GetApiTauriSshMachinesEventsQueryMachineId = string;
-export type GetApiTauriSshMachinesEventsQuerySinceSeq = number;
-export type GetApiTauriSshSyncPreviewResponse = { plugins?: { name?: string; spec?: string; syncable?: false | true; reason?: string }[]; skills?: { name?: string; root?: string }[]; error?: string };
-export type PostApiTauriSshSyncApplyResponse = { items?: { kind?: string; name?: string; root?: string; ok?: false | true; error?: string; log?: string }[]; error?: string };
-
-export interface PostApiTauriSshSettingsBody {
- enabled?: false | true;
-}
-export interface PostApiTauriSshMachinesBody {
- machineId?: string;
- row?: { name?: string; host?: string; port?: number; user?: string; remotePort?: number; profileName?: string; startCommand?: string; color?: string; tintBorder?: false | true };
- secrets?: { password?: string; passphrase?: string };
-}
-export interface DeleteApiTauriSshMachinesBody {
- machineId?: string;
-}
-export interface PostApiTauriSshMachinesTestBody {
- machineId?: string;
-}
-export interface PostApiTauriSshMachinesConnectBody {
- machineId?: string;
-}
-export interface PostApiTauriSshMachinesDisconnectBody {
- machineId?: string;
-}
-export interface PostApiTauriSshMachinesInstallBody {
- machineId?: string;
-}
-export interface PostApiTauriSshSyncApplyBody {
- machineId?: string;
- plugins?: { name?: string; spec?: string }[];
- skills?: { name?: string; root?: string }[];
-}
-export interface GetApiTauriSshMachinesEventsQuery {
- machineId?: GetApiTauriSshMachinesEventsQueryMachineId;
- sinceSeq?: GetApiTauriSshMachinesEventsQuerySinceSeq;
-}
diff --git a/packages/dsh-tauri-ssh/src/client/components/ssh-section.test.tsx b/packages/dsh-tauri-ssh/src/client/components/ssh-section.test.tsx
deleted file mode 100644
index 288120a8..00000000
--- a/packages/dsh-tauri-ssh/src/client/components/ssh-section.test.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-
-import { store } from '../store/index'
-import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
-import { SshSection } from './ssh-section'
-
-const baseURL = '/api/tauri/ssh'
-
-vi.mock('dsh-tauri-ui/client', async () => (await import('../test-utils/ui-mock')).uiMock)
-
-vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
-
-function bootWire(options: { enabled?: boolean } = {}) {
- let enabled = options.enabled ?? false
- answer((call) => {
- if (call.url === `${baseURL}/settings` && call.http === 'GET')
- return replies.ok({ enabled })
- if (call.url === `${baseURL}/settings`) {
- enabled = call.body.enabled === true
- return replies.ok({ enabled })
- }
- if (call.url === `${baseURL}/session/role`)
- return replies.ok({ remote: false })
- return replies.ok({ enabled, items: [], discovered: [] })
- })
-}
-
-const t = (key: string) => `t:${key}`
-
-beforeEach(() => {
- resetWire()
- store.machines.reset()
-})
-
-afterEach(() => {
- cleanup()
-})
-
-describe('sshSection', () => {
- it('未启用时只渲染 Hero(图标 + 描述 + 开启按钮),不渲染 Tabs 内容', async () => {
- bootWire()
- render(<SshSection t={t as never} />)
-
- await waitFor(() => expect(screen.getByTestId('ssh-hero')).toBeTruthy())
- expect(screen.getByText('t:hero.title')).toBeTruthy()
- expect(screen.getByText('t:hero.desc')).toBeTruthy()
- expect(screen.getByTestId('ssh-enable').textContent).toBe('t:hero.enable')
- expect(screen.queryByTestId('ssh-tabs')).toBeNull()
- expect(screen.queryByText('t:tabs.machines')).toBeNull()
- })
-
- it('点击开启:settings.set 落定后原位切换到 Tabs(SSH 机器 / 同步到远端)', async () => {
- bootWire()
- render(<SshSection t={t as never} />)
- await waitFor(() => expect(screen.getByTestId('ssh-enable')).toBeTruthy())
-
- fireEvent.click(screen.getByTestId('ssh-enable'))
- await waitFor(() => expect(screen.getByTestId('ssh-tabs')).toBeTruthy())
- expect(sent.some(call => call.url === `${baseURL}/settings` && call.http === 'POST')).toBe(true)
- const tabs = screen.getAllByRole('tab')
- expect(tabs.map(tab => tab.textContent)).toEqual(['t:tabs.machines', 't:tabs.sync'])
- expect(screen.queryByTestId('ssh-hero')).toBeNull()
- expect(screen.getByRole('tab', { selected: true }).textContent).toBe('t:tabs.machines')
- })
-
- it('点击禁用:保存关闭开关后回到 Hero 并卸载已访问的面板', async () => {
- bootWire({ enabled: true })
- render(<SshSection t={t as never} />)
- await waitFor(() => expect(screen.getByTestId('ssh-tabs')).toBeTruthy())
- fireEvent.click(screen.getByRole('tab', { name: 't:tabs.sync' }))
-
- const button = screen.getByRole('button', { name: 't:disable' })
- expect(screen.getByTestId('ssh-tabs').contains(button)).toBe(true)
- fireEvent.click(button)
-
- await waitFor(() => expect(screen.getByTestId('ssh-enable').textContent).toBe('t:hero.enable'))
- expect(sent.filter(call => call.url === `${baseURL}/settings` && call.http === 'POST').map(call => call.body)).toEqual([{ enabled: false }])
- expect(store.machines.enabled).toBe(false)
- expect(screen.queryByTestId('ssh-tabs')).toBeNull()
- expect(screen.queryAllByRole('tabpanel', { hidden: true })).toEqual([])
- })
-
- it('已启用:Tabs 默认停在「SSH 机器」,切换后渲染同步面板且已访问面板保持挂载', async () => {
- bootWire({ enabled: true })
- render(<SshSection t={t as never} />)
- await waitFor(() => expect(screen.getByTestId('ssh-tabs')).toBeTruthy())
-
- const machinesPanel = document.getElementById('dsh-tauri-ssh-tabs-machines-panel')
- expect(machinesPanel?.hasAttribute('hidden')).toBe(false)
-
- fireEvent.click(screen.getByRole('tab', { name: 't:tabs.sync' }))
- await waitFor(() => {
- expect(document.getElementById('dsh-tauri-ssh-tabs-sync-panel')?.hasAttribute('hidden')).toBe(false)
- })
- expect(document.getElementById('dsh-tauri-ssh-tabs-machines-panel')?.hasAttribute('hidden')).toBe(true)
- })
-
- it('壳层 deep link:分区匹配时落到指定标签页,别的分区不动', async () => {
- bootWire({ enabled: true })
- render(<SshSection t={t as never} />)
- await waitFor(() => expect(screen.getByTestId('ssh-tabs')).toBeTruthy())
-
- window.dispatchEvent(new MessageEvent('message', {
- data: { type: 'dsh://settings:open', section: 'dsh-tauri-ssh-sync', tab: 'sync' },
- source: window,
- }))
- expect(screen.getByRole('tab', { selected: true }).textContent).toBe('t:tabs.machines')
-
- window.dispatchEvent(new MessageEvent('message', {
- data: { type: 'dsh://settings:open', section: 'dsh-tauri-ssh', tab: 'sync' },
- source: window,
- }))
- await waitFor(() => {
- expect(screen.getByRole('tab', { selected: true }).textContent).toBe('t:tabs.sync')
- })
- })
-
- it('读取开关失败(插件未加载):Hero 呈现本地化的不可用提示而非原生解析异常', async () => {
- answer(() => replies.http(405))
- render(<SshSection t={t as never} />)
-
- await waitFor(() => expect(screen.getByTestId('ssh-hero-error')).toBeTruthy())
- expect(screen.getByTestId('ssh-hero-error').textContent).toBe('t:error.unavailable')
- })
-})
diff --git a/packages/dsh-tauri-ssh/src/client/components/ssh-section.tsx b/packages/dsh-tauri-ssh/src/client/components/ssh-section.tsx
deleted file mode 100644
index c87e8e48..00000000
--- a/packages/dsh-tauri-ssh/src/client/components/ssh-section.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-import type { ReactNode } from 'react'
-import type { SshKey } from '../locales/index'
-import { Button, Globe, Icon, SegmentedControl } from 'dsh-tauri-ui/client'
-import { cn, useListenParent, useStore } from 'dsh-tauri/client'
-import { useEffect, useState } from 'react'
-import { SETTINGS_OPEN_MESSAGE, SETTINGS_SECTION_ID, SSH_TAB_MACHINES, SSH_TAB_SYNC, SSH_TABS_ID } from '../constants/index'
-import * as service from '../service/machines'
-import { store } from '../store/index'
-import { errorTextOf } from '../utils/error'
-import { MachinesSection } from './machines-section'
-import { SyncPanel } from './sync-panel'
-
-type SshTab = typeof SSH_TAB_MACHINES | typeof SSH_TAB_SYNC
-
-interface SshSectionProps {
- t: (key: SshKey) => string
-}
-
-const TAB_KEYS: Record<SshTab, SshKey> = {
- [SSH_TAB_MACHINES]: 'tabs.machines',
- [SSH_TAB_SYNC]: 'tabs.sync',
-}
-
-export function SshSection({ t }: SshSectionProps): ReactNode {
- const state = useStore(store.machines)
- const [tab, setTab] = useState<SshTab>(SSH_TAB_MACHINES)
- const [visited, setVisited] = useState<ReadonlySet<SshTab>>(() => new Set<SshTab>([SSH_TAB_MACHINES]))
-
- function openTab(next: SshTab): void {
- setTab(next)
- setVisited(previous => previous.has(next) ? previous : new Set<SshTab>([...previous, next]))
- }
-
- useEffect(() => {
- if (store.machines.enabled === null)
- void service.loadSettings()
- }, [])
-
- useListenParent(SETTINGS_OPEN_MESSAGE, (message) => {
- if (message.section !== SETTINGS_SECTION_ID)
- return
- if (message.tab === SSH_TAB_MACHINES || message.tab === SSH_TAB_SYNC)
- openTab(message.tab)
- })
-
- if (state.enabled === null) {
- return (
- <div className="flex flex-col gap-[12px] max-w-[960px] text-primary" data-testid="ssh-section">
- <p className="m-0 text-[12px] leading-[18px] text-tertiary">{t('loading')}</p>
- </div>
- )
- }
-
- if (state.enabled === false) {
- return (
- <div className="flex flex-col gap-[12px] max-w-[960px] text-primary" data-testid="ssh-section">
- <div className="mt-[4px] flex flex-col items-center gap-[12px] rounded-[12px] border-[0.5px] border-border-l2 bg-layer-1 px-[24px] py-[40px] text-center" data-testid="ssh-hero">
- <span className="inline-flex h-[44px] w-[44px] items-center justify-center rounded-full bg-[var(--dsw-alias-surface-tinted)] text-brand" aria-hidden="true">
- <Icon as={Globe} size={22} />
- </span>
- <h2 className="m-0 text-[22px] leading-[32px] font-semibold text-primary">{t('hero.title')}</h2>
- <p className="m-0 max-w-[460px] text-[13px] leading-[21px] text-secondary">{t('hero.desc')}</p>
- {state.error !== null
- ? <p className="m-0 text-[12px] leading-[18px] text-error" role="alert" data-testid="ssh-hero-error">{errorTextOf(state.error, t)}</p>
- : null}
- <Button
- variant="primary"
- size="sm"
- disabled={state.enabling}
- data-testid="ssh-enable"
- onClick={() => void service.setEnabled(true)}
- >
- {state.enabling ? t('hero.enabling') : t('hero.enable')}
- </Button>
- </div>
- </div>
- )
- }
-
- const tabs: SshTab[] = [SSH_TAB_MACHINES, SSH_TAB_SYNC]
-
- return (
- <div className="flex flex-col gap-[12px] max-w-[960px] text-primary" data-testid="ssh-section">
- <div className="flex flex-wrap justify-between items-center gap-[8px]" data-testid="ssh-tabs">
- <SegmentedControl
- id={SSH_TABS_ID}
- label={t('nav')}
- value={tab}
- options={tabs.map(value => ({ value, label: t(TAB_KEYS[value]) }))}
- onChange={(next) => {
- if (next === SSH_TAB_MACHINES || next === SSH_TAB_SYNC)
- openTab(next)
- }}
- />
- <Button variant="ghost" size="sm" disabled={state.enabling} onClick={() => void service.setEnabled(false)}>
- {t('disable')}
- </Button>
- </div>
- {tabs.filter(value => value === tab || visited.has(value)).map((value) => {
- const selected = value === tab
- return (
- <div
- key={value}
- id={`${SSH_TABS_ID}-${value}-panel`}
- className={cn('min-w-0 flex-col gap-[12px]', selected ? 'flex' : 'hidden')}
- role="tabpanel"
- aria-labelledby={`${SSH_TABS_ID}-${value}`}
- hidden={!selected}
- >
- {value === SSH_TAB_MACHINES
- ? <MachinesSection t={t} />
- : <SyncPanel t={t} />}
- </div>
- )
- })}
- </div>
- )
-}
diff --git a/packages/dsh-tauri-ssh/src/client/constants/index.ts b/packages/dsh-tauri-ssh/src/client/constants/index.ts
deleted file mode 100644
index dfc524f5..00000000
--- a/packages/dsh-tauri-ssh/src/client/constants/index.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { SSH_PLUGIN_NAME as PLUGIN_ID } from '../../shared/constants'
-
-export { SSH_PLUGIN_NAME as PLUGIN_ID } from '../../shared/constants'
-
-export const SETTINGS_SECTION_SLOT = 'settings.section'
-export const SETTINGS_SECTION_ID = PLUGIN_ID
-export const SETTINGS_SECTION_ORDER = 50
-
-export const SSH_TAB_MACHINES = 'machines'
-export const SSH_TAB_SYNC = 'sync'
-export const SSH_TABS_ID = 'dsh-tauri-ssh-tabs'
-export const SETTINGS_OPEN_MESSAGE = 'dsh://settings:open'
-
-export const REMOTE_BRIDGE_PING_COMMAND = 'remote_bridge_ping'
-export const REMOTE_OPEN_WINDOW_COMMAND = 'remote_open_window'
-
-export const LOCALE_EFFECT = `${PLUGIN_ID}: locale`
-export const SECTION_EFFECT = `${PLUGIN_ID}: settings section`
-export const POLL_EFFECT = `${PLUGIN_ID}: machine polling`
diff --git a/packages/dsh-tauri-ssh/src/client/index.test.ts b/packages/dsh-tauri-ssh/src/client/index.test.ts
deleted file mode 100644
index 293990a5..00000000
--- a/packages/dsh-tauri-ssh/src/client/index.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import type { ClientContext } from 'dsh-tauri/client'
-import { describe, expect, it, vi } from 'vitest'
-
-import { SshSection } from './components/ssh-section.tsx'
-import { LOCALE_EFFECT, PLUGIN_ID, POLL_EFFECT, SECTION_EFFECT } from './constants/index'
-import { apply, inject, name } from './index'
-
-vi.mock('dsh-tauri/client', async () => {
- const seam = await import('./test-utils/client-mock')
- return {
- ...seam.clientMock,
- defineLocale: () => ({ NS: 'dsh-tauri-ssh', text: (key: string) => `t:${key}`, registerLocale: () => () => {} }),
- }
-})
-
-vi.mock('dsh-tauri-ui/client', () => ({}))
-
-interface ScriptedCtx {
- ctx: ClientContext
- slots: { inject: ReturnType<typeof vi.fn>, register: ReturnType<typeof vi.fn> }
- effects: { run: (this: unknown) => unknown, label: string }[]
-}
-
-function scriptedCtx(): ScriptedCtx {
- const slots = {
- inject: vi.fn((_slot: string, _callback: () => unknown) => () => {}),
- register: vi.fn(() => 'registration'),
- }
- const effects: { run: (this: unknown) => unknown, label: string }[] = []
- const ctx = {
- effect: (run: (this: unknown) => unknown, label: string) => { effects.push({ run, label }) },
- get: () => undefined,
- locale: {},
- slots,
- } as unknown as ClientContext
- return { ctx, slots, effects }
-}
-
-describe('dsh-tauri-ssh client plugin', () => {
- it('declares its inject topology and its plugin name', () => {
- expect(inject).toEqual(['slots', 'locale'])
- expect(name).toBe(PLUGIN_ID)
- })
-
- it('registers three declarative effects on activation and does no eager work', () => {
- const { ctx, slots, effects } = scriptedCtx()
- apply(ctx)
- expect(effects.map(entry => entry.label)).toEqual([LOCALE_EFFECT, SECTION_EFFECT, POLL_EFFECT])
- for (const entry of effects)
- expect(entry.run).toBeTypeOf('function')
- expect(slots.inject).not.toHaveBeenCalled()
- expect(slots.register).not.toHaveBeenCalled()
- })
-
- it('registers the single SSH settings section through the slots service', () => {
- const { ctx, slots, effects } = scriptedCtx()
- apply(ctx)
- const section = effects.find(entry => entry.label === SECTION_EFFECT)
- const dispose = section?.run.call(ctx)
- expect(slots.inject).toHaveBeenCalledTimes(1)
- 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?: unknown
- }
- expect(options.name).toBe('settings.section')
- expect(options.id).toBe(PLUGIN_ID)
- expect(options.order).toBe(50)
- expect(options.label()).toBe('t:nav')
- expect(options.locale).toBe(PLUGIN_ID)
- expect(options.inject).toBeUndefined()
- expect(slots.register.mock.calls[0]?.[1]).toBe(SshSection)
- expect(dispose).toBeTypeOf('function')
- ;(dispose as () => void)()
- })
-})
diff --git a/packages/dsh-tauri-ssh/src/client/register/section.ts b/packages/dsh-tauri-ssh/src/client/register/section.ts
deleted file mode 100644
index 1218152c..00000000
--- a/packages/dsh-tauri-ssh/src/client/register/section.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { ClientContext } from 'dsh-tauri/client'
-import { defineRegister } from 'dsh-tauri/client'
-import { SshSection } from '../components/ssh-section'
-import { SETTINGS_SECTION_ID, SETTINGS_SECTION_ORDER, SETTINGS_SECTION_SLOT } from '../constants/index'
-import { locale } from '../locales/index'
-
-export const sectionFeature = defineRegister<ClientContext>((controller, ctx) => {
- controller.add(ctx.slots.inject(SETTINGS_SECTION_SLOT as never, () => ctx.slots.register({
- name: SETTINGS_SECTION_SLOT,
- id: SETTINGS_SECTION_ID,
- order: SETTINGS_SECTION_ORDER,
- label: () => locale.text('nav'),
- locale: locale.NS,
- } as never, SshSection as never)))
-})
diff --git a/packages/dsh-tauri-ssh/src/client/store/index.ts b/packages/dsh-tauri-ssh/src/client/store/index.ts
deleted file mode 100644
index 2a469b9c..00000000
--- a/packages/dsh-tauri-ssh/src/client/store/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { machines } from './modules/machines'
-import { sync } from './modules/sync'
-
-export const store = { machines, sync }
diff --git a/packages/dsh-tauri-ssh/src/client/types/index.ts b/packages/dsh-tauri-ssh/src/client/types/index.ts
deleted file mode 100644
index 400684e0..00000000
--- a/packages/dsh-tauri-ssh/src/client/types/index.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-export type MachineLifecycleState
- = | 'disconnected'
- | 'testing'
- | 'connecting'
- | 'connected'
- | 'reconnecting'
- | 'given-up'
-
-export interface ServiceResult {
- ok: boolean
- error?: string
-}
-
-export function isLifecycleState(value: unknown): value is MachineLifecycleState {
- return value === 'disconnected'
- || value === 'testing'
- || value === 'connecting'
- || value === 'connected'
- || value === 'reconnecting'
- || value === 'given-up'
-}
-
-export interface MachineRow {
- id: string
- name: string
- host: string
- port: number
- user: string
- hasPassword: boolean
- hasPassphrase: boolean
- remotePort: number
- profileName?: string
- startCommand?: string
- color?: string
- tintBorder?: boolean
-}
-
-export interface SecretValues {
- password?: string
- passphrase?: string
-}
-
-export type ProgressPhase = 'handshake' | 'installing' | 'starting' | 'probing' | 'syncing'
-
-export interface MachineStatus {
- state: MachineLifecycleState
- nextRetryAt?: number
- authMethod?: 'agent' | 'key' | 'password'
- tunnelBaseUrl?: string
- lastError?: string
- dshMissing?: boolean
- progress?: { phase: ProgressPhase, attempt?: number, total?: number, item?: string, log?: string }
-}
-
-export interface MachineListSnapshot {
- machines: MachineRow[]
- discovered: MachineRow[]
- statuses: Record<string, MachineStatus>
-}
-
-export interface InstallResult {
- dshPath: string
- credentialsCopied: boolean
- credentialsError?: string
-}
-
-export interface SshMachineEvent {
- seq: number
- ts: string
- machineId: string
- stage: string
- line: string
- terminal?: 'success' | 'failed'
- reason?: string
-}
-
-export interface SyncPluginItem {
- name: string
- spec: string
- syncable: boolean
- reason?: string
-}
-
-export interface SyncSkillItem {
- name: string
- root: string
-}
-
-export interface SyncPreview {
- plugins: SyncPluginItem[]
- skills: SyncSkillItem[]
-}
-
-export interface SyncItemResult {
- kind: 'plugin' | 'skill'
- name: string
- root?: string
- ok: boolean
- error?: string
- log?: string
-}
-
-export interface SyncApplyResult {
- items: SyncItemResult[]
-}
-
-export interface RemoteBridge {
- probe: () => Promise<unknown>
- openWindow: (machineId: string, url: string) => Promise<unknown>
-}
diff --git a/packages/dsh-tauri-ssh/src/client/utils/error.ts b/packages/dsh-tauri-ssh/src/client/utils/error.ts
deleted file mode 100644
index 3dd15595..00000000
--- a/packages/dsh-tauri-ssh/src/client/utils/error.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import type { SshKey } from '../locales/index'
-import { isTransportError } from '../apis/parsers'
-
-export function errorTextOf(message: string, t: (key: SshKey) => string): string {
- return isTransportError(message) ? t('error.unavailable') : message
-}
diff --git a/packages/dsh-tauri-ssh/src/host/apply.ts b/packages/dsh-tauri-ssh/src/host/apply.ts
deleted file mode 100644
index ac206210..00000000
--- a/packages/dsh-tauri-ssh/src/host/apply.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import type { Context } from '@deepseek-ai/cordis'
-import type z from 'schemastery'
-import type { Config as SshRemoteConfig } from './config/schema'
-import type { SshHostContext } from './types/index'
-import { SSH_PLUGIN_NAME } from '../shared/constants'
-import { resetRuntime, setHostConfig, setMachineDeps, setSyncDeps } from './config/runtime'
-import { ConfigSchema } from './config/schema'
-import { server } from './server'
-import { machine } from './service/machine'
-import { transport } from './service/transport'
-import { packSkills, profileAllowlistReader, profileDependenciesReader, skillRootsScanner } from './utils/local'
-
-const SSH_START_EFFECT = `${SSH_PLUGIN_NAME}: start`
-
-const SSH_ROUTES_EFFECT = `${SSH_PLUGIN_NAME}: routes`
-
-const SSH_RUNTIME_EFFECT = `${SSH_PLUGIN_NAME}: host runtime`
-
-export const name = SSH_PLUGIN_NAME
-
-export const inject = ['webServer', 'connection']
-
-export const Config: z<SshRemoteConfig> = ConfigSchema
-
-export function apply(ctx: SshHostContext, config: SshRemoteConfig): void {
- setHostConfig(config)
- setMachineDeps({
- transport,
- emitStatus: () => {}, // keep: 进度出口注入点,故意留空——状态另经 status() 与事件环读取
- localAllowlist: profileAllowlistReader(),
- })
- setSyncDeps({
- profileDependencies: profileDependenciesReader(),
- scanSkills: skillRootsScanner(),
- packSkills,
- ...config.installTimeoutMs === undefined ? {} : { commandTimeoutMs: config.installTimeoutMs },
- })
-
- ctx.effect(() => {
- void machine.start().catch(() => undefined)
- }, SSH_START_EFFECT)
-
- ctx.effect(() => server(ctx as unknown as Context), SSH_ROUTES_EFFECT)
-
- ctx.effect(() => () => {
- void machine.dispose()
- resetRuntime()
- }, SSH_RUNTIME_EFFECT)
-}
-
-export default { apply, Config, inject, name }
diff --git a/packages/dsh-tauri-ssh/src/host/config/constants.ts b/packages/dsh-tauri-ssh/src/host/config/constants.ts
deleted file mode 100644
index f959dc10..00000000
--- a/packages/dsh-tauri-ssh/src/host/config/constants.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export const EVENT_RING_CAPACITY = 500
-
-export const DEFAULT_REMOTE_PROFILE = 'remote'
-
-export const REMOTE_ROOT = '.dsh-desktop'
diff --git a/packages/dsh-tauri-ssh/src/host/config/runtime.ts b/packages/dsh-tauri-ssh/src/host/config/runtime.ts
deleted file mode 100644
index a3ea0f4e..00000000
--- a/packages/dsh-tauri-ssh/src/host/config/runtime.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import type { MachineDeps, MachineState } from '../service/machine.types'
-import type { SyncDeps } from '../service/sync.types'
-import type { MachineId, MachineProfile, SshMachineEvent } from '../types/index'
-import type { Config } from './schema'
-import { homedir } from 'node:os'
-import process from 'node:process'
-import { join } from 'pathe'
-import { EVENT_RING_CAPACITY } from './constants'
-
-export const machineProfiles = new Map<MachineId, MachineProfile>()
-
-export const machineStates = new Map<MachineId, MachineState>()
-
-export const machineTable: { enabled: boolean, machines: Map<MachineId, MachineProfile> } = {
- enabled: false,
- machines: new Map(),
-}
-
-export const eventBuffers = new Map<MachineId, { seq: number, events: SshMachineEvent[] }>()
-
-let config: Config | undefined
-let homeDir = homedir()
-let sshDir = ''
-let statePath = ''
-let knownHostsPath = ''
-let eventCapacity = EVENT_RING_CAPACITY
-let deps: MachineDeps | undefined
-let syncDeps: SyncDeps | undefined
-
-export function harnessHome(): string {
- return process.env.DSH_HOME ?? join(homedir(), '.dsh')
-}
-
-export function hostConfig(): Config {
- if (config === undefined)
- throw new TypeError('hostConfig: 插件配置尚未装配,apply.ts 需先调用 setHostConfig(config)')
- return config
-}
-
-export function setHostConfig(next: Config): void {
- config = next
- homeDir = homedir()
- sshDir = next.sshDir ?? join(homeDir, '.ssh')
- statePath = next.statePath ?? join(harnessHome(), 'ssh', 'machines.json')
- knownHostsPath = next.knownHostsPath ?? join(harnessHome(), 'ssh', 'known-hosts.json')
-}
-
-export function stateDocumentPath(): string {
- return statePath === '' ? join(harnessHome(), 'ssh', 'machines.json') : statePath
-}
-
-export function setKnownHostsPath(path: string): void {
- knownHostsPath = path
-}
-
-export function knownHostsFilePath(): string {
- return knownHostsPath === '' ? join(harnessHome(), 'ssh', 'known-hosts.json') : knownHostsPath
-}
-
-export function sshDirPath(): string {
- return sshDir === '' ? join(homedir(), '.ssh') : sshDir
-}
-
-export function homeDirPath(): string {
- return homeDir
-}
-
-export function setEventCapacity(capacity: number): void {
- eventCapacity = capacity
-}
-
-export function eventRingCapacity(): number {
- return eventCapacity
-}
-
-export function setMachineDeps(next: MachineDeps): void {
- deps = next
-}
-
-export function machineRuntimeDeps(): MachineDeps {
- if (deps === undefined)
- throw new TypeError('machineRuntimeDeps: 连接面依赖尚未装配,apply.ts 需先调用 setMachineDeps(deps)')
- return deps
-}
-
-export function setSyncDeps(next: SyncDeps): void {
- syncDeps = next
-}
-
-export function syncRuntimeDeps(): SyncDeps {
- if (syncDeps === undefined)
- throw new TypeError('syncRuntimeDeps: 同步面依赖尚未装配,apply.ts 需先调用 setSyncDeps(deps)')
- return syncDeps
-}
-
-export function resetRuntime(): void {
- // 使在途 attempt 失效:未完成的 performConnect/performInstall 恢复执行时会比对 generation,
- // 若不等则不再对外拨号(否则它们的续跑会读到下一个 runtime 的 deps,把连接打到别人的 transport 上)。
- for (const target of machineStates.values())
- target.generation += 1
- config = undefined
- homeDir = homedir()
- sshDir = ''
- statePath = ''
- knownHostsPath = ''
- eventCapacity = EVENT_RING_CAPACITY
- deps = undefined
- syncDeps = undefined
- machineProfiles.clear()
- machineStates.clear()
- machineTable.enabled = false
- machineTable.machines.clear()
- eventBuffers.clear()
-}
diff --git a/packages/dsh-tauri-ssh/src/host/server/index.ts b/packages/dsh-tauri-ssh/src/host/server/index.ts
deleted file mode 100644
index 5e4fadff..00000000
--- a/packages/dsh-tauri-ssh/src/host/server/index.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { defineWebServer } from 'dsh-h3'
-import { guard } from 'dsh-tauri'
-import machinesConnect from './routes/machines/connect/post'
-import machinesDelete from './routes/machines/delete'
-import machinesDisconnect from './routes/machines/disconnect/post'
-import machinesEvents from './routes/machines/events/get'
-import machinesGet from './routes/machines/get'
-import machinesInstall from './routes/machines/install/post'
-import machinesPost from './routes/machines/post'
-import machinesTest from './routes/machines/test/post'
-import sessionRole from './routes/session/role/get'
-import settingsGet from './routes/settings/get'
-import settingsPost from './routes/settings/post'
-import syncApply from './routes/sync/apply/post'
-import syncPreview from './routes/sync/preview/get'
-
-export const server = defineWebServer((app) => {
- app.use(guard)
- app.get('/api/tauri/ssh/settings', settingsGet)
- app.post('/api/tauri/ssh/settings', settingsPost)
- app.get('/api/tauri/ssh/session/role', sessionRole)
- app.get('/api/tauri/ssh/machines', machinesGet)
- app.post('/api/tauri/ssh/machines', machinesPost)
- app.delete('/api/tauri/ssh/machines', machinesDelete)
- app.post('/api/tauri/ssh/machines/test', machinesTest)
- app.post('/api/tauri/ssh/machines/connect', machinesConnect)
- app.post('/api/tauri/ssh/machines/disconnect', machinesDisconnect)
- app.post('/api/tauri/ssh/machines/install', machinesInstall)
- app.get('/api/tauri/ssh/machines/events', machinesEvents)
- app.get('/api/tauri/ssh/sync/preview', syncPreview)
- app.post('/api/tauri/ssh/sync/apply', syncApply)
-})
diff --git a/packages/dsh-tauri-ssh/src/host/server/routes/session/role/get.ts b/packages/dsh-tauri-ssh/src/host/server/routes/session/role/get.ts
deleted file mode 100644
index b2dca970..00000000
--- a/packages/dsh-tauri-ssh/src/host/server/routes/session/role/get.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import type { EventHandlerRequest } from 'h3'
-import type { SshSessionRoleResponse } from '../../index.types'
-import { defineEventHandler } from 'h3'
-import { session } from '../../../../service/session'
-import { guarded } from '../../index.utils'
-
-export default defineEventHandler<EventHandlerRequest, Promise<SshSessionRoleResponse>>(async event =>
- guarded(event, async () => {
- const role = session.role()
- return { ...role, role: role.remote ? 'remote' : 'local' }
- }))
diff --git a/packages/dsh-tauri-ssh/src/host/service/machine.types.ts b/packages/dsh-tauri-ssh/src/host/service/machine.types.ts
deleted file mode 100644
index 40d99440..00000000
--- a/packages/dsh-tauri-ssh/src/host/service/machine.types.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import type {
- MachineId,
- SshAuthMethod,
- SshInstallResult,
- SshLink,
- SshMachineStatus,
- SshProgress,
- SshSession,
- SshTunnelHandle,
-} from '../types/index'
-import type { WorkspaceAllowlist } from '../utils/allowlist'
-import type { BundledPluginsTree } from '../utils/plugins-sync'
-import type { SshTransport } from './transport.types'
-
-export interface MachineState {
- generation: number
- phase: 'disconnected' | 'testing' | 'connecting' | 'connected' | 'reconnecting' | 'given-up'
- connecting?: Promise<SshLink>
- installing?: Promise<SshInstallResult>
- session?: SshSession
- tunnel?: SshTunnelHandle
- link?: SshLink
- lastError?: string
- dshMissing?: boolean
- progress?: SshProgress
- reconnect?: ReconnectState
- preferredTunnelPort?: number
- authMethod?: SshAuthMethod
-}
-
-export interface ReconnectState {
- generation: number
- attempt: number
- nextRetryAt?: number
- timer?: NodeJS.Timeout
- reasons: string[]
-}
-
-export interface MachineDeps {
- transport: SshTransport
- emitStatus: (machineId: MachineId, status: SshMachineStatus) => void
- localAllowlist: () => WorkspaceAllowlist
- bundledPluginsTree?: BundledPluginsTree
-}
diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.types.ts b/packages/dsh-tauri-ssh/src/host/service/transport.types.ts
deleted file mode 100644
index 3db973f9..00000000
--- a/packages/dsh-tauri-ssh/src/host/service/transport.types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { Buffer } from 'node:buffer'
-import type { MachineProfile, SshSession } from '../types/index'
-import type { ResolvedSshAuth } from '../utils/ssh-config'
-
-export type SshCredentialsResolver = (profile: MachineProfile) => Promise<ResolvedSshAuth>
-
-export interface SshTransportOptions {
- readyTimeoutMs: number
- resolveProfile: SshCredentialsResolver
- keepaliveIntervalMs?: number
- keepaliveCountMax?: number
-}
-
-export type SshHostKeyVerifier = (label: string, hostKey: Buffer) => boolean | Promise<boolean>
-
-export interface SshTransport {
- connect: (
- profile: MachineProfile,
- hostKeyVerifier: SshHostKeyVerifier,
- options: SshTransportOptions,
- signal?: AbortSignal,
- ) => Promise<SshSession>
-}
-
-export type SshConnectFailureKind
- = | 'key-rejected'
- | 'password-rejected'
- | 'unreachable'
- | 'other'
diff --git a/packages/dsh-tauri-ssh/src/host/storage/index.ts b/packages/dsh-tauri-ssh/src/host/storage/index.ts
deleted file mode 100644
index d3cf2365..00000000
--- a/packages/dsh-tauri-ssh/src/host/storage/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import { createStorage } from 'unstorage'
-import { sshDocumentDriver } from './driver'
-
-export const storage = createStorage({ driver: sshDocumentDriver() })
diff --git a/packages/dsh-tauri-ssh/src/host/types/index.ts b/packages/dsh-tauri-ssh/src/host/types/index.ts
deleted file mode 100644
index d29d8bd8..00000000
--- a/packages/dsh-tauri-ssh/src/host/types/index.ts
+++ /dev/null
@@ -1,232 +0,0 @@
-import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
-import type { Buffer } from 'node:buffer'
-
-export type MachineId = string & { readonly __machineId: unique symbol }
-
-// eslint-disable-next-line ts/no-redeclare -- 品牌类型惯用法:值与类型同名
-export function MachineId(id: string): MachineId {
- return id as MachineId
-}
-
-export interface MachineProfile {
- id: MachineId
- name: string
- host: string
- port: number
- user: string
- password?: string
- passphrase?: string
- remotePort: number
- profileName?: string
- startCommand?: string
- color?: string
- tintBorder?: boolean
-}
-
-export interface MachineView {
- id: MachineId
- name: string
- host: string
- port: number
- user: string
- hasPassword: boolean
- hasPassphrase: boolean
- remotePort: number
- profileName?: string
- startCommand?: string
- color?: string
- tintBorder?: boolean
-}
-
-export interface MachineSaveRow {
- name: string
- host: string
- port: number
- user: string
- remotePort: number
- profileName?: string
- startCommand?: string
- color?: string
- tintBorder?: boolean
-}
-
-export interface MachineSecretWrite {
- password?: string
- passphrase?: string
-}
-
-export type SshConnectionState
- = | 'disconnected'
- | 'testing'
- | 'connecting'
- | 'connected'
- | 'reconnecting'
- | 'given-up'
-
-export type SshAuthMethod = 'agent' | 'key' | 'password'
-
-export type SshProgressPhase = 'handshake' | 'starting' | 'probing' | 'installing' | 'syncing'
-
-export interface SshProgress {
- phase: SshProgressPhase
- attempt?: number
- total?: number
- item?: string
- log?: string
-}
-
-export interface SshMachineStatus {
- machineId: MachineId
- state: SshConnectionState
- tunnelBaseUrl?: string
- lastError?: string
- dshMissing?: boolean
- progress?: SshProgress
- nextRetryAt?: number
- authMethod?: SshAuthMethod
-}
-
-export interface SshLink {
- machineId: MachineId
- tunnelBaseUrl: string
-}
-
-export type SshTestResult
- = | { ok: true, banner: string }
- | { ok: false, message: string }
-
-export type SshMachineStage
- = | 'probe'
- | 'download'
- | 'verify'
- | 'install'
- | 'launch'
- | 'ready'
- | 'failed'
- | 'auth'
- | 'reconnect'
-
-export type SshMachineTerminal = 'success' | 'failed'
-
-export interface SshMachineEvent {
- seq: number
- ts: string
- machineId: MachineId
- stage: SshMachineStage
- line: string
- terminal?: SshMachineTerminal
- reason?: string
-}
-
-export interface SshMachineEventsPage {
- events: SshMachineEvent[]
- nextSeq: number
-}
-
-export interface SshInstallResult {
- installed: string[]
- dshRef: string
- dshVersion: string
- dshPath: string
- credentialsCopied: boolean
- credentialsError?: string
-}
-
-export type SshErrorCode
- = | 'machine-not-found'
- | 'machine-connect-failed'
- | 'machine-bootstrap-failed'
- | 'machine-dsh-missing'
- | 'machine-install-failed'
- | 'machine-ssh-error'
- | 'machine-reconnecting'
- | 'machine-sync-failed'
-
-export type SyncSkillRoot = 'dsh' | 'agents'
-
-export interface SyncPluginItem {
- name: string
- spec: string
- syncable: boolean
- reason?: string
-}
-
-export interface SyncSkillItem {
- name: string
- root: SyncSkillRoot
-}
-
-export interface SyncPreview {
- plugins: SyncPluginItem[]
- skills: SyncSkillItem[]
-}
-
-export interface SyncPluginRef {
- name: string
- spec: string
-}
-
-export interface SyncSkillRef {
- name: string
- root: SyncSkillRoot
-}
-
-export interface SyncItemResult {
- kind: 'plugin' | 'skill'
- name: string
- root?: SyncSkillRoot
- ok: boolean
- error?: string
- log?: string
-}
-
-export interface SyncApplyResult {
- items: SyncItemResult[]
-}
-
-export class SshError extends Error {
- constructor(readonly code: SshErrorCode, readonly machineId: MachineId, message: string) {
- super(message)
- this.name = 'SshError'
- }
-}
-
-export interface SshExecResult {
- code: number | null
- stdout: string
- stderr: string
-}
-
-export interface SshExecOptions {
- timeoutMs?: number
- onData?: (chunk: string) => void
- stdinData?: Buffer
-}
-
-export interface TunnelHeaderInjection {
- cookie: string | undefined
-}
-
-export interface SshTunnelHandle {
- localPort: number
- close: () => Promise<void>
-}
-
-export interface SshSession {
- readonly authMethod?: SshAuthMethod | undefined
- exec: (command: string, options?: SshExecOptions) => Promise<SshExecResult>
- openTunnel: (remotePort: number, preferredLocalPort?: number, injection?: TunnelHeaderInjection) => Promise<SshTunnelHandle>
- onClosed: (callback: () => void) => void
- close: () => Promise<void>
-}
-
-export type HostWebRoute = WebRoute
-
-export interface HostWebServer {
- register: (route: HostWebRoute) => () => void
-}
-
-export interface SshHostContext {
- webServer: HostWebServer
- effect: (execute: () => (() => void) | void, label?: string) => unknown
-}
diff --git a/packages/dsh-tauri-ssh/src/index.ts b/packages/dsh-tauri-ssh/src/index.ts
deleted file mode 100644
index 840ddcda..00000000
--- a/packages/dsh-tauri-ssh/src/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { apply, Config, default, inject, name } from './host/apply'
-export type { SshMachineEvent, SshMachineEventsPage, SshMachineStage, SshMachineTerminal } from './host/types/index'
diff --git a/packages/dsh-tauri-ssh/tsdown.config.ts b/packages/dsh-tauri-ssh/tsdown.config.ts
deleted file mode 100644
index 8161184d..00000000
--- a/packages/dsh-tauri-ssh/tsdown.config.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { defineDshConfig } from '../dsh-tauri-tsdown/src/index.ts'
-
-// Host half (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-ui/src/client/register/settings-open.test.ts b/packages/dsh-tauri-ui/src/client/register/settings-open.test.ts
index cc1724ac..5642df43 100644
--- a/packages/dsh-tauri-ui/src/client/register/settings-open.test.ts
+++ b/packages/dsh-tauri-ui/src/client/register/settings-open.test.ts
@@ -24,13 +24,13 @@ describe('registerSettingsOpen', () => {
it('opens the settings overlay at the requested section on the host message', () => {
mocks.listenParent.mockImplementation((handler: (message: unknown) => void, types: unknown) => {
expect(types).toBe(SETTINGS_OPEN_MESSAGE)
- handler({ type: SETTINGS_OPEN_MESSAGE, section: 'dsh-tauri-ssh-sync' })
+ handler({ type: SETTINGS_OPEN_MESSAGE, section: 'dsh-tauri-remote-sync' })
return () => {}
})
const controller = { add: vi.fn() }
;(registerSettingsOpen as (controller: unknown) => void)(controller)
expect(mocks.listenParent).toHaveBeenCalledOnce()
- expect(mocks.openAt).toHaveBeenCalledWith('dsh-tauri-ssh-sync')
+ expect(mocks.openAt).toHaveBeenCalledWith('dsh-tauri-remote-sync')
})
it('ignores non-string sections and opens without a target', () => {
@@ -38,7 +38,7 @@ describe('registerSettingsOpen', () => {
handler({ type: SETTINGS_OPEN_MESSAGE, section: 42 })
handler({ type: SETTINGS_OPEN_MESSAGE })
// 旧形状(payload 包装)不再被识别:层级读错就是静默失效的根因
- handler({ type: SETTINGS_OPEN_MESSAGE, payload: { section: 'dsh-tauri-ssh' } })
+ handler({ type: SETTINGS_OPEN_MESSAGE, payload: { section: 'dsh-tauri-remote' } })
return () => {}
})
;(registerSettingsOpen as (controller: unknown) => void)({ add: vi.fn() })
diff --git a/packages/dsh-tauri-ui/src/client/styles/index.ts b/packages/dsh-tauri-ui/src/client/styles/index.ts
index 6865c8c4..95982126 100644
--- a/packages/dsh-tauri-ui/src/client/styles/index.ts
+++ b/packages/dsh-tauri-ui/src/client/styles/index.ts
@@ -297,6 +297,9 @@ const TAILWINDCSS_GENERATED = `
.h-\\[4px\\] {
height: 4px;
}
+ .h-\\[6px\\] {
+ height: 6px;
+ }
.h-\\[8px\\] {
height: 8px;
}
@@ -1177,6 +1180,9 @@ const TAILWINDCSS_GENERATED = `
.pb-\\[9px\\] {
padding-bottom: 9px;
}
+ .pb-\\[12px\\] {
+ padding-bottom: 12px;
+ }
.pb-\\[16px\\] {
padding-bottom: 16px;
}
@@ -1332,6 +1338,10 @@ const TAILWINDCSS_GENERATED = `
--tw-font-weight: var(--font-weight-semibold);
font-weight: var(--font-weight-semibold);
}
+ .tracking-\\[2px\\] {
+ --tw-tracking: 2px;
+ letter-spacing: 2px;
+ }
.\\[overflow-wrap\\:anywhere\\] {
overflow-wrap: anywhere;
}
@@ -1380,9 +1390,6 @@ const TAILWINDCSS_GENERATED = `
.text-\\[var\\(--dsw-alias-state-warning-primary\\,var\\(--dsw-alias-label-tertiary\\)\\)\\] {
color: var(--dsw-alias-state-warning-primary,var(--dsw-alias-label-tertiary));
}
- .text-brand {
- color: var(--dsw-alias-brand-primary);
- }
.text-business {
color: var(--dsw-alias-state-business-primary);
}
@@ -1422,6 +1429,9 @@ const TAILWINDCSS_GENERATED = `
.lowercase {
text-transform: lowercase;
}
+ .uppercase {
+ text-transform: uppercase;
+ }
.tabular-nums {
--tw-numeric-spacing: tabular-nums;
font-variant-numeric: var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,);
@@ -1514,6 +1524,11 @@ const TAILWINDCSS_GENERATED = `
transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));
transition-duration: var(--tw-duration, var(--default-transition-duration));
}
+ .transition-\\[width\\] {
+ transition-property: width;
+ transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));
+ transition-duration: var(--tw-duration, var(--default-transition-duration));
+ }
.transition-colors {
transition-property: color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to;
transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));
@@ -1528,6 +1543,10 @@ const TAILWINDCSS_GENERATED = `
--tw-duration: 150ms;
transition-duration: 150ms;
}
+ .duration-200 {
+ --tw-duration: 200ms;
+ transition-duration: 200ms;
+ }
.duration-\\[120ms\\] {
--tw-duration: 120ms;
transition-duration: 120ms;
@@ -2786,6 +2805,10 @@ const TAILWINDCSS_GENERATED = `
syntax: "*";
inherits: false;
}
+@property --tw-tracking {
+ syntax: "*";
+ inherits: false;
+}
@property --tw-ordinal {
syntax: "*";
inherits: false;
@@ -2992,6 +3015,7 @@ const TAILWINDCSS_GENERATED = `
--tw-border-style: solid;
--tw-leading: initial;
--tw-font-weight: initial;
+ --tw-tracking: initial;
--tw-ordinal: initial;
--tw-slashed-zero: initial;
--tw-numeric-figure: initial;
diff --git a/packages/dsh-tauri-ui/src/client/ui/settings-sidebar.tsx b/packages/dsh-tauri-ui/src/client/ui/settings-sidebar.tsx
index 75e69ab7..3e6d0c4b 100644
--- a/packages/dsh-tauri-ui/src/client/ui/settings-sidebar.tsx
+++ b/packages/dsh-tauri-ui/src/client/ui/settings-sidebar.tsx
@@ -7,7 +7,7 @@ import { SlotOutlet } from '@deepseek-ai/dsh-client-ui-renderer'
import { clamp, cn, isEmpty, useEventListener, useStore } from 'dsh-tauri/client'
import { useEffect, useRef, useState } from 'react'
import { Icon } from '../components/icon'
-import { ArrowLeft, Cubes3Overlap, Database, Gear, Ghost, LayoutSplitSideContentRight, PersonPencil, Puzzle, Server, Smartphone, Tray } from '../components/icons'
+import { ArrowLeft, Cubes3Overlap, Database, Gear, Ghost, Globe, LayoutSplitSideContentRight, PersonPencil, Puzzle, Smartphone, Tray } from '../components/icons'
import { Input } from '../components/official'
import {
RAIL_WIDTH_DEFAULT,
@@ -32,7 +32,7 @@ const Icons: Record<string, IconComponent | undefined> = {
'agent-presets': Cubes3Overlap,
'dsh-tauri-archive': Tray,
'plugins': Puzzle,
- 'dsh-tauri-ssh': Server,
+ 'dsh-tauri-remote': Globe,
'dsh-tauri-pet-settings': Ghost,
'better-sidebar': LayoutSplitSideContentRight,
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4ad5c673..472750b3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -315,6 +315,9 @@ catalogs:
'@types/node':
specifier: ^22.10.0
version: 22.20.1
+ '@types/qrcode':
+ specifier: ^1.5.5
+ version: 1.5.6
'@types/react':
specifier: ^19.2.18
version: 19.2.18
@@ -359,6 +362,9 @@ catalogs:
pathe:
specifier: ^2.0.3
version: 2.0.3
+ qrcode:
+ specifier: ^1.5.4
+ version: 1.5.4
schemastery:
specifier: ^3.18.0
version: 3.18.0
@@ -421,7 +427,7 @@ importers:
version: 2.4.4
dsh-pet-component:
specifier: catalog:runtime
i18next:
specifier: catalog:runtime
version: 26.3.6([email protected])
@@ -803,15 +809,15 @@ importers:
dsh-tauri-pet:
specifier: workspace:*
version: link:../dsh-tauri-pet
+ dsh-tauri-remote:
+ specifier: workspace:*
+ version: link:../dsh-tauri-remote
dsh-tauri-rightclick:
specifier: workspace:*
version: link:../dsh-tauri-rightclick
dsh-tauri-scheduler:
specifier: workspace:*
version: link:../dsh-tauri-scheduler
- dsh-tauri-ssh:
- specifier: workspace:*
- version: link:../dsh-tauri-ssh
dsh-tauri-ui:
specifier: workspace:*
version: link:../dsh-tauri-ui
@@ -1024,7 +1030,7 @@ importers:
specifier: catalog:cli
- packages/dsh-tauri-rightclick:
+ packages/dsh-tauri-remote:
dependencies:
dsh-h3:
specifier: 'catalog:'
@@ -1032,49 +1038,85 @@ importers:
dsh-tauri:
specifier: workspace:*
version: link:../dsh-tauri
+ dsh-tauri-ui:
+ specifier: workspace:*
+ version: link:../dsh-tauri-ui
h3:
specifier: 'catalog:'
version: 2.0.1
- lodash-es:
+ pathe:
specifier: catalog:utils
- version: 4.18.1
+ version: 2.0.3
+ schemastery:
+ specifier: catalog:utils
+ version: 3.18.0
+ ssh2:
+ specifier: catalog:utils
+ version: 1.17.0
+ yaml:
+ specifier: catalog:testing
+ version: 2.9.0
devDependencies:
- '@types/lodash-es':
+ '@testing-library/dom':
+ specifier: catalog:testing
+ version: 10.4.2
+ '@testing-library/react':
+ specifier: catalog:testing
+ '@types/node':
specifier: catalog:types
- version: 4.17.12
+ version: 22.20.1
+ '@types/qrcode':
+ specifier: catalog:types
+ version: 1.5.6
+ '@types/react':
+ specifier: catalog:types
+ version: 19.2.18
+ '@types/react-dom':
+ specifier: catalog:types
+ version: 19.2.4(@types/[email protected])
+ '@types/ssh2':
+ specifier: catalog:types
+ version: 1.15.6
dsh-tauri-tsdown:
specifier: workspace:*
version: link:../dsh-tauri-tsdown
- dsh-tauri-ui:
- specifier: workspace:*
- version: link:../dsh-tauri-ui
+ jsdom:
+ specifier: catalog:testing
+ version: 26.1.0
+ qrcode:
+ specifier: catalog:utils
+ version: 1.5.4
+ react:
+ specifier: catalog:runtime
+ version: 19.2.8
+ react-dom:
+ specifier: catalog:runtime
+ version: 19.2.8([email protected])
tsdown:
specifier: catalog:cli
+ typescript:
+ specifier: catalog:cli
+ version: 5.8.3
+ vitest:
+ specifier: catalog:testing
- packages/dsh-tauri-scheduler:
+ packages/dsh-tauri-rightclick:
dependencies:
- cron-schedule:
- specifier: catalog:utils
- version: 6.0.0
dsh-h3:
specifier: 'catalog:'
version: 0.2.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@genapi/[email protected])([email protected])
dsh-tauri:
specifier: workspace:*
version: link:../dsh-tauri
- dsh-tauri-ui:
- specifier: workspace:*
- version: link:../dsh-tauri-ui
h3:
specifier: 'catalog:'
version: 2.0.1
lodash-es:
specifier: catalog:utils
version: 4.18.1
- pathe:
- specifier: catalog:utils
- version: 2.0.3
devDependencies:
'@types/lodash-es':
specifier: catalog:types
@@ -1082,15 +1124,18 @@ importers:
dsh-tauri-tsdown:
specifier: workspace:*
version: link:../dsh-tauri-tsdown
+ dsh-tauri-ui:
+ specifier: workspace:*
+ version: link:../dsh-tauri-ui
tsdown:
specifier: catalog:cli
- vitest:
- specifier: catalog:testing
- packages/dsh-tauri-ssh:
+ packages/dsh-tauri-scheduler:
dependencies:
+ cron-schedule:
+ specifier: catalog:utils
+ version: 6.0.0
dsh-h3:
specifier: 'catalog:'
version: 0.2.1(@deepseek-ai/[email protected])(@deepseek-ai/[email protected](@deepseek-ai/[email protected]))(@genapi/[email protected])([email protected])
@@ -1103,55 +1148,22 @@ importers:
h3:
specifier: 'catalog:'
version: 2.0.1
+ lodash-es:
+ specifier: catalog:utils
+ version: 4.18.1
pathe:
specifier: catalog:utils
version: 2.0.3
- schemastery:
- specifier: catalog:utils
- version: 3.18.0
- ssh2:
- specifier: catalog:utils
- version: 1.17.0
- yaml:
- specifier: catalog:testing
- version: 2.9.0
devDependencies:
- '@testing-library/dom':
- specifier: catalog:testing
- version: 10.4.2
- '@testing-library/react':
- specifier: catalog:testing
- '@types/node':
- specifier: catalog:types
- version: 22.20.1
- '@types/react':
- specifier: catalog:types
- version: 19.2.18
- '@types/react-dom':
- specifier: catalog:types
- version: 19.2.4(@types/[email protected])
- '@types/ssh2':
+ '@types/lodash-es':
specifier: catalog:types
- version: 1.15.6
+ version: 4.17.12
dsh-tauri-tsdown:
specifier: workspace:*
version: link:../dsh-tauri-tsdown
- jsdom:
- specifier: catalog:testing
- version: 26.1.0
- react:
- specifier: catalog:runtime
- version: 19.2.8
- react-dom:
- specifier: catalog:runtime
- version: 19.2.8([email protected])
tsdown:
specifier: catalog:cli
- typescript:
- specifier: catalog:cli
- version: 5.8.3
vitest:
specifier: catalog:testing
@@ -3685,6 +3697,9 @@ packages:
resolution: {integrity: sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==}
+
resolution: {integrity: sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw==}
peerDependencies:
@@ -4198,6 +4213,10 @@ packages:
resolution: {integrity: sha512-tixWYgm5ZoOD+3g6UTea91eow5z6AAHaho3g0V9CNSNb45gM8SmflpAc+GRd1InC4AqN/07Unrgp56Y94N9hJQ==}
engines: {node: '>=20.19.0'}
+ resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-xxWVywk6a6Arlk+hymeycyn/VgqEfLDxupvhH/xiY5SJ/18kmi9o6MiO320DCUzypORHLtvh0I4i04tUhCNHNQ==}
@@ -4273,6 +4292,9 @@ packages:
resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}
+ resolution: {integrity: sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==}
+
resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}
engines: {node: '>=12'}
@@ -4454,6 +4476,10 @@ packages:
supports-color:
optional: true
+ resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==}
+ engines: {node: '>=0.10.0'}
+
resolution: {integrity: sha512-G7Cqgaelq68XHJNGlZ7lrNQyhZGsFqpwtGFexqUv4IQdjKoSYF7ipZ9UuTJZUSQXFj/XaoBLuEVIVqr8EJngEQ==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
@@ -4531,6 +4557,9 @@ packages:
resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==}
engines: {node: '>=0.3.1'}
+ resolution: {integrity: sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==}
+
resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
@@ -5012,6 +5041,10 @@ packages:
resolution: {integrity: sha512-afd4O7zpqHeRyg4PfDQsXmlDe2PfdHtJt6Akt8jOWaApLOZk5JXs6VMR29lz03pRe9mpykrRCYIYxaJYcfpncQ==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==}
engines: {node: '>=10'}
@@ -5521,6 +5554,10 @@ packages:
resolution: {integrity: sha512-xIqbzPMBYArJRmPGUZD9CzV9wOqmVtQnaAn3wrj3s6WYW0bQvPI7x+sPYUGmDTYMHefVK//zc6HEYZ1qnxIK+Q==}
+ resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==}
engines: {node: '>=10'}
@@ -5964,10 +6001,18 @@ packages:
resolution: {integrity: sha512-Q6Bekk5wpzW5qIyUP4gdMEujObYstZl6DMMOSenwBvV0BlE5LkDwkjs5yHbZmdCEq2o4RJx4tE1vwxFVf2FG1w==}
engines: {node: '>=16.17'}
+ resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==}
engines: {node: '>=10'}
@@ -5980,6 +6025,10 @@ packages:
resolution: {integrity: sha512-MyIV3ZA/PmyBN/ud8vV9XzwTrNtR4jFrObymZYnZqMmW0zA8Z17vnT0rBgFE/TlohB+YCHqXMgZzb3Csp49vqg==}
engines: {node: '>=14.16'}
+ resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==}
engines: {node: '>= 14'}
@@ -6081,6 +6130,10 @@ packages:
resolution: {integrity: sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==}
engines: {node: '>=4'}
+ resolution: {integrity: sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==}
+ engines: {node: '>=10.13.0'}
+
resolution: {integrity: sha512-rqGldoFOzjalWzlPtzAi/RcjAyep+Pjl4QUKJ6/oEZXzhVAX79GS/i8gjhQT715g75kTkyfHjL9eBPGZ9Co++Q==}
@@ -6152,6 +6205,11 @@ packages:
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==}
+ engines: {node: '>=10.13.0'}
+ hasBin: true
+
resolution: {integrity: sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==}
@@ -6290,6 +6348,9 @@ packages:
resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==}
+
resolution: {integrity: sha512-yE7KUfFvaBFzGPs5H3Ops1RevfUEsDc5Iz65rOwWg4lE8HJSYtle77uul3+573457oHvBKuHYDl/xqUkKpEEdw==}
engines: {node: '>=18'}
@@ -6407,6 +6468,9 @@ packages:
resolution: {integrity: sha512-ZYkZLAvKTKQXWuh5XpBw7CdbSzagarX39WyZ2H07CDLC5/KfsRGlIXV8d4+tfqX1M7916mRqR1QfNHSij+c9Pw==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==}
+
resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==}
@@ -6674,7 +6738,6 @@ packages:
resolution: {integrity: sha512-z+kNuv1rwM1POQIufDUVrdNc/uGy0ueRVafCyDH39IdHxin4JXgB8DNGSPoqdIpcOpqUoRbNreK8NxENFmlhKw==}
engines: {node: '>=20.19.0'}
- deprecated: Including an unexpected breaking change (copy behavior)
hasBin: true
peerDependencies:
'@arethetypeswrong/core': ^0.18.1
@@ -7059,6 +7122,9 @@ packages:
resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==}
+
resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}
engines: {node: '>= 8'}
@@ -7078,6 +7144,10 @@ packages:
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}
engines: {node: '>=10'}
@@ -7112,6 +7182,9 @@ packages:
resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}
+ resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==}
+
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
engines: {node: '>=10'}
@@ -7135,10 +7208,18 @@ packages:
engines: {node: '>= 14.6'}
hasBin: true
+ resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==}
engines: {node: '>=12'}
@@ -8954,13 +9035,14 @@ snapshots:
'@reause/shared': 0.1.7([email protected])
react: 19.2.8
dependencies:
'@reause/shared': 0.1.4([email protected])
react: 19.2.8
optionalDependencies:
change-case: 5.4.4
idb-keyval: 6.3.0
+ qrcode: 1.5.4
dependencies:
@@ -9476,6 +9558,10 @@ snapshots:
dependencies:
undici-types: 6.21.0
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.20.1
+
dependencies:
'@types/react': 19.2.18
@@ -10106,6 +10192,8 @@ snapshots:
+
@@ -10213,6 +10301,12 @@ snapshots:
+ dependencies:
+ string-width: 4.2.3
+ strip-ansi: 6.0.1
+ wrap-ansi: 6.2.0
+
dependencies:
string-width: 4.2.3
@@ -10369,6 +10463,8 @@ snapshots:
dependencies:
ms: 2.1.3
+
@@ -10425,6 +10521,8 @@ snapshots:
+
@@ -10470,11 +10568,11 @@ snapshots:
- crossws
- ocache
dependencies:
'@gravity-ui/icons': 2.21.0([email protected])
'@reause/core': 0.1.7([email protected])
- '@reause/integrations': 0.1.4([email protected])([email protected])([email protected])
css-render: 0.15.14
idb-keyval: 6.3.0
react: 19.2.8
@@ -11066,6 +11164,11 @@ snapshots:
+ dependencies:
+ locate-path: 5.0.0
+ path-exists: 4.0.0
+
dependencies:
locate-path: 6.0.0
@@ -11571,6 +11674,10 @@ snapshots:
type-fest: 4.26.0
userhome: 1.0.1
+ dependencies:
+ p-locate: 4.1.0
+
dependencies:
p-locate: 5.0.0
@@ -12213,10 +12320,18 @@ snapshots:
dependencies:
p-timeout: 6.1.4
+ dependencies:
+ p-try: 2.2.0
+
dependencies:
yocto-queue: 0.1.0
+ dependencies:
+ p-limit: 2.3.0
+
dependencies:
p-limit: 3.1.0
@@ -12225,6 +12340,8 @@ snapshots:
+
dependencies:
'@tootallnate/quickjs-emscripten': 0.23.0
@@ -12322,6 +12439,8 @@ snapshots:
+
dependencies:
yaml: 2.9.0
@@ -12403,6 +12522,12 @@ snapshots:
+ dependencies:
+ dijkstrajs: 1.0.3
+ pngjs: 5.0.0
+ yargs: 15.4.1
+
@@ -12555,6 +12680,8 @@ snapshots:
+
@@ -12710,6 +12837,8 @@ snapshots:
dependencies:
type-fest: 4.41.0
+
@@ -13322,6 +13451,8 @@ snapshots:
tr46: 5.1.1
webidl-conversions: 7.0.0
+
dependencies:
isexe: 2.0.0
@@ -13337,6 +13468,12 @@ snapshots:
+ dependencies:
+ ansi-styles: 4.3.0
+ string-width: 4.2.3
+ strip-ansi: 6.0.1
+
dependencies:
ansi-styles: 4.3.0
@@ -13361,6 +13498,8 @@ snapshots:
+
@@ -13376,8 +13515,27 @@ snapshots:
+ dependencies:
+ camelcase: 5.3.1
+ decamelize: 1.2.0
+
+ dependencies:
+ cliui: 6.0.0
+ decamelize: 1.2.0
+ find-up: 4.1.0
+ get-caller-file: 2.0.5
+ require-directory: 2.1.1
+ require-main-filename: 2.0.0
+ set-blocking: 2.0.0
+ string-width: 4.2.3
+ which-module: 2.0.1
+ y18n: 4.0.3
+ yargs-parser: 18.1.3
+
dependencies:
cliui: 8.0.1
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 7c349d9f..9d103045 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -222,6 +222,7 @@ catalogs:
types:
'@types/lodash-es': ^4.17.12
'@types/node': ^22.10.0
+ '@types/qrcode': ^1.5.5
'@types/react': ^19.2.18
'@types/react-dom': ^19.2.4
'@types/semver': ^7.8.0
@@ -238,6 +239,7 @@ catalogs:
lodash-es: ^4.18.1
ofetch: ^1.5.1
pathe: ^2.0.3
+ qrcode: ^1.5.4
schemastery: ^3.18.0
smol-toml: ^1.3.1
ssh2: ^1.17.0
diff --git a/scripts/e2e-ssh-data-plane.mjs b/scripts/e2e-ssh-data-plane.mjs
index a6612845..f6667585 100644
--- a/scripts/e2e-ssh-data-plane.mjs
+++ b/scripts/e2e-ssh-data-plane.mjs
@@ -1,6 +1,6 @@
#!/usr/bin/env node
/**
- * S5 整体验收·数据面全旅程驱动脚本(无头,直驱 /api/tauri/ssh REST 面)。
+ * S5 整体验收·数据面全旅程驱动脚本(无头,直驱 /api/tauri/remote REST 面)。
*
* 旅程(对应 S5 Spec 验收标准 2 的可自动化子集):
* POST /machines(dev 真机,含 color/tintBorder/startCommand)
@@ -16,7 +16,7 @@
* → 303 + set-cookie),随后所有请求带着该 Cookie 走;也可以直接给 `--cookie`
* (例如从浏览器 DevTools 复制)。
*
- * 用法(先起一个挂了 dsh-tauri-ssh 的本地 dsh 实例,见
+ * 用法(先起一个挂了 dsh-tauri-remote 的本地 dsh 实例,见
* docs/testing/s5-ssh-e2e-evidence.md 的复现步骤):
* node scripts/e2e-ssh-data-plane.mjs \
* --base http://127.0.0.1:3185 --token <alpha-token> \
@@ -45,7 +45,7 @@ const remotePort = Number(argOf('remote-port', '3082'))
const startCommand = argOf('start-command', '')
const outPath = argOf('out', '')
const machineId = randomUUID()
-const api = `${base}/api/tauri/ssh`
+const api = `${base}/api/tauri/remote`
let cookie = argOf('cookie', '')
const lines = []
@@ -118,7 +118,7 @@ async function main() {
const settings = await request('GET', '/settings')
if (settings.enabled !== true)
- throw new Error('dsh-tauri-ssh 未启用:先 POST /api/tauri/ssh/settings {"enabled":true}')
+ throw new Error('dsh-tauri-remote 未启用:先 POST /api/tauri/remote/settings {"enabled":true}')
log(`# S5 SSH 数据面全旅程 — ${new Date().toISOString()}`)
log(`base=${base} host=${host} user=${user} sshPort=${sshPort} remotePort=${remotePort}`)
diff --git a/soruce/dsh-bridge b/soruce/dsh-bridge
new file mode 160000
index 00000000..06ef0e27
--- /dev/null
+++ b/soruce/dsh-bridge
@@ -0,0 +1 @@
+Subproject commit 06ef0e273c9cec8f405b50d4599d541d623552ee
diff --git a/src-tauri/resources/manifest.jsonc b/src-tauri/resources/manifest.jsonc
index 0b185dad..60f7b726 100644
--- a/src-tauri/resources/manifest.jsonc
+++ b/src-tauri/resources/manifest.jsonc
@@ -145,10 +145,10 @@
"repo": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/tree/main/packages/dsh-tauri-model"
},
{
- "id": "dsh-tauri-ssh",
- "spec": "dsh-tauri-ssh",
- "name": "DSH Tauri SSH",
- "repo": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-ssh"
+ "id": "dsh-tauri-remote",
+ "spec": "dsh-tauri-remote",
+ "name": "DSH Tauri Remote",
+ "repo": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-remote"
},
{
"id": "dsh-tauri-notification",
diff --git a/src-tauri/src/bridge/remote.rs b/src-tauri/src/bridge/remote.rs
index b81b5c43..7fbaee29 100644
--- a/src-tauri/src/bridge/remote.rs
+++ b/src-tauri/src/bridge/remote.rs
@@ -6,19 +6,23 @@ use tauri::{AppHandle, Manager};
fn remote_method(method: &str) -> Result<(reqwest::Method, &str), String> {
if !matches!(
method,
- "GET /api/tauri/ssh/machines"
- | "POST /api/tauri/ssh/machines"
- | "DELETE /api/tauri/ssh/machines"
- | "POST /api/tauri/ssh/machines/connect"
- | "POST /api/tauri/ssh/machines/disconnect"
- | "GET /api/tauri/ssh/machines/events"
- | "POST /api/tauri/ssh/machines/install"
- | "POST /api/tauri/ssh/machines/test"
- | "GET /api/tauri/ssh/session/role"
- | "GET /api/tauri/ssh/settings"
- | "POST /api/tauri/ssh/settings"
- | "POST /api/tauri/ssh/sync/apply"
- | "GET /api/tauri/ssh/sync/preview"
+ "GET /api/tauri/remote/machines"
+ | "POST /api/tauri/remote/machines"
+ | "DELETE /api/tauri/remote/machines"
+ | "POST /api/tauri/remote/machines/connect"
+ | "POST /api/tauri/remote/machines/disconnect"
+ | "GET /api/tauri/remote/machines/events"
+ | "POST /api/tauri/remote/machines/install"
+ | "POST /api/tauri/remote/machines/test"
+ | "GET /api/tauri/remote/session/role"
+ | "GET /api/tauri/remote/settings"
+ | "POST /api/tauri/remote/settings"
+ | "POST /api/tauri/remote/sync/apply"
+ | "GET /api/tauri/remote/sync/preview"
+ | "GET /api/tauri/remote/access"
+ | "POST /api/tauri/remote/access"
+ | "POST /api/tauri/remote/access/tunnel"
+ | "DELETE /api/tauri/remote/access/tunnel"
) {
return Err(format!("REMOTE_METHOD_INVALID: {method}"));
}
@@ -126,7 +130,7 @@ fn sanitize_label_part(raw: &str) -> String {
}
/// 校验隧道 URL:仅接受 `127.0.0.1` host 的明文 http(隧道由引擎建在
-/// `127.0.0.1:<port>`,见插件 `SshLink`;与 capability `remote.urls`
+/// `127.0.0.1:<port>`,见插件 `RemoteLink`;与 capability `remote.urls`
/// `http://127.0.0.1:*` 精确对齐——`localhost`/`[::1]` 过守卫却命不中
/// capability,弹窗会静默退化为无 IPC 的纯 web,故在命令侧一并拒绝)。
fn validate_loopback_http_url(raw: &str) -> Result<tauri::Url, String> {
@@ -177,7 +181,7 @@ fn open_window_args(machine_id: &str, url: &str) -> Result<(String, Option<tauri
/// 打开(已开则聚焦)`remote-<machineId>` 弹窗窗口,加载壳层应用。
///
/// 壳不自存机器状态:前端按窗口 label 自解析目标机器并切换(机器状态经
-/// `/api/tauri/ssh/machines` 轮询获取);`url` 只做回环校验。重复调用聚焦已有窗口(不
+/// `/api/tauri/remote/machines` 轮询获取);`url` 只做回环校验。重复调用聚焦已有窗口(不
/// 重复建窗);失败返回带前缀的可读错误,由调用方(S4 面板按钮)呈现。
#[tauri::command]
pub fn remote_open_window(
@@ -251,21 +255,25 @@ mod tests {
}
#[test]
- fn remote_whitelist_accepts_all_thirteen_generated_endpoints() {
+ fn remote_whitelist_accepts_all_seventeen_generated_endpoints() {
for method in [
- "GET /api/tauri/ssh/machines",
- "POST /api/tauri/ssh/machines",
- "DELETE /api/tauri/ssh/machines",
- "POST /api/tauri/ssh/machines/connect",
- "POST /api/tauri/ssh/machines/disconnect",
- "GET /api/tauri/ssh/machines/events",
- "POST /api/tauri/ssh/machines/install",
- "POST /api/tauri/ssh/machines/test",
- "GET /api/tauri/ssh/session/role",
- "GET /api/tauri/ssh/settings",
- "POST /api/tauri/ssh/settings",
- "POST /api/tauri/ssh/sync/apply",
- "GET /api/tauri/ssh/sync/preview",
+ "GET /api/tauri/remote/machines",
+ "POST /api/tauri/remote/machines",
+ "DELETE /api/tauri/remote/machines",
+ "POST /api/tauri/remote/machines/connect",
+ "POST /api/tauri/remote/machines/disconnect",
+ "GET /api/tauri/remote/machines/events",
+ "POST /api/tauri/remote/machines/install",
+ "POST /api/tauri/remote/machines/test",
+ "GET /api/tauri/remote/session/role",
+ "GET /api/tauri/remote/settings",
+ "POST /api/tauri/remote/settings",
+ "POST /api/tauri/remote/sync/apply",
+ "GET /api/tauri/remote/sync/preview",
+ "GET /api/tauri/remote/access",
+ "POST /api/tauri/remote/access",
+ "POST /api/tauri/remote/access/tunnel",
+ "DELETE /api/tauri/remote/access/tunnel",
] {
let (verb, path) = remote_method(method).expect("generated endpoint must be allowed");
assert_eq!(format!("{verb} {path}"), method);
@@ -277,18 +285,21 @@ mod tests {
for method in [
"",
"GET",
- "get /api/tauri/ssh/machines",
- "PUT /api/tauri/ssh/machines",
- "GET /api/tauri/ssh/machines/connect",
- "POST /api/tauri/ssh/machines/events",
- "GET /api/tauri/ssh/machines?machineId=m1",
- "GET /api/tauri/ssh/machines/../settings",
- "GET /api/tauri/ssh/machines/",
- "GET /api/tauri/ssh/machines",
- "GET /api/tauri/ssh/machines\n",
- "GET http://127.0.0.1:3080/api/tauri/ssh/machines",
- "GET https://example.com/api/tauri/ssh/machines",
- "GET //example.com/api/tauri/ssh/machines",
+ "get /api/tauri/remote/machines",
+ "PUT /api/tauri/remote/machines",
+ "GET /api/tauri/remote/machines/connect",
+ "POST /api/tauri/remote/machines/events",
+ "GET /api/tauri/remote/machines?machineId=m1",
+ "GET /api/tauri/remote/machines/../settings",
+ "GET /api/tauri/remote/machines/",
+ "GET /api/tauri/remote/machines",
+ "GET /api/tauri/remote/machines\n",
+ "PUT /api/tauri/remote/access",
+ "GET /api/tauri/remote/access/tunnel",
+ "POST /api/tauri/remote/access?x=1",
+ "GET http://127.0.0.1:3080/api/tauri/remote/machines",
+ "GET https://example.com/api/tauri/remote/machines",
+ "GET //example.com/api/tauri/remote/machines",
"GET /api/other",
] {
assert_eq!(
@@ -301,7 +312,7 @@ mod tests {
#[tokio::test]
async fn remote_get_forwards_encoded_primitive_query_without_body() {
let (port, server) = response_server("200 OK", "", r#"{"events":[]}"#).await;
- let (verb, path) = remote_method("GET /api/tauri/ssh/machines/events").unwrap();
+ let (verb, path) = remote_method("GET /api/tauri/remote/machines/events").unwrap();
let result = remote_request(
port,
verb,
@@ -319,7 +330,7 @@ mod tests {
.nth(1)
.unwrap();
let url = tauri::Url::parse(&format!("http://127.0.0.1{target}")).unwrap();
- assert_eq!(url.path(), "/api/tauri/ssh/machines/events");
+ assert_eq!(url.path(), "/api/tauri/remote/machines/events");
let query: std::collections::BTreeMap<_, _> = url.query_pairs().into_owned().collect();
assert_eq!(
query,
@@ -335,8 +346,8 @@ mod tests {
#[tokio::test]
async fn remote_mutations_forward_json_body_and_preserve_http_verb() {
for method in [
- "POST /api/tauri/ssh/machines/connect",
- "DELETE /api/tauri/ssh/machines",
+ "POST /api/tauri/remote/machines/connect",
+ "DELETE /api/tauri/remote/machines",
] {
let (port, server) = response_server("200 OK", "", r#"{"ok":true}"#).await;
let (verb, path) = remote_method(method).unwrap();
@@ -360,8 +371,8 @@ mod tests {
#[tokio::test]
async fn remote_absent_or_null_payload_sends_no_query_or_body() {
for method in [
- "GET /api/tauri/ssh/machines",
- "POST /api/tauri/ssh/machines/install",
+ "GET /api/tauri/remote/machines",
+ "POST /api/tauri/remote/machines/install",
] {
for payload in [None, Some(Value::Null)] {
let (port, server) = response_server("200 OK", "", "null").await;
@@ -386,7 +397,7 @@ mod tests {
("201 Created", "not JSON"),
] {
let (port, server) = response_server(status, "", body).await;
- let (verb, path) = remote_method("POST /api/tauri/ssh/settings").unwrap();
+ let (verb, path) = remote_method("POST /api/tauri/remote/settings").unwrap();
let result = remote_request(port, verb, path, None).await;
server.await.unwrap();
assert_eq!(result.unwrap(), Value::Null);
@@ -397,7 +408,7 @@ mod tests {
async fn remote_missing_api_is_distinct_from_other_http_failures() {
for (status, expected) in [("404 Not Found", "404"), ("405 Method Not Allowed", "405")] {
let (port, server) = response_server(status, "", r#"{"error":"disabled"}"#).await;
- let (verb, path) = remote_method("GET /api/tauri/ssh/settings").unwrap();
+ let (verb, path) = remote_method("GET /api/tauri/remote/settings").unwrap();
let result = remote_request(port, verb, path, None).await;
server.await.unwrap();
assert_eq!(
@@ -419,7 +430,7 @@ mod tests {
("", "HTTP 500"),
] {
let (port, server) = response_server("500 Internal Server Error", "", body).await;
- let (verb, path) = remote_method("POST /api/tauri/ssh/machines/test").unwrap();
+ let (verb, path) = remote_method("POST /api/tauri/remote/machines/test").unwrap();
let result = remote_request(port, verb, path, None).await;
server.await.unwrap();
assert_eq!(
@@ -434,7 +445,7 @@ mod tests {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
- let (verb, path) = remote_method("GET /api/tauri/ssh/machines").unwrap();
+ let (verb, path) = remote_method("GET /api/tauri/remote/machines").unwrap();
let error = remote_request(port, verb, path, None).await.unwrap_err();
assert!(
error.starts_with("REMOTE_REQUEST_FAILED:"),
@@ -452,7 +463,7 @@ mod tests {
] {
let (port, server) =
response_server("302 Found", &format!("Location: {location}\r\n"), "").await;
- let (verb, path) = remote_method("GET /api/tauri/ssh/machines").unwrap();
+ let (verb, path) = remote_method("GET /api/tauri/remote/machines").unwrap();
let result = remote_request(port, verb, path, None).await;
server.await.unwrap();
assert_eq!(result.unwrap_err(), "REMOTE_REQUEST_FAILED: HTTP 302");
@@ -465,7 +476,7 @@ mod tests {
#[tokio::test]
async fn remote_invalid_get_payload_is_rejected_before_connecting() {
- let (verb, path) = remote_method("GET /api/tauri/ssh/machines/events").unwrap();
+ let (verb, path) = remote_method("GET /api/tauri/remote/machines/events").unwrap();
for payload in [json!([]), json!({"machineId": {"nested": true}})] {
let error = remote_request(0, verb.clone(), path, Some(payload))
.await
diff --git a/src/apis/http.test.ts b/src/apis/http.test.ts
index de61b60e..5ad59ae0 100644
--- a/src/apis/http.test.ts
+++ b/src/apis/http.test.ts
@@ -13,8 +13,8 @@ describe('generated remote API transport', () => {
await expect(getMachines()).resolves.toEqual({ enabled: true, items: [] })
await expect(getMachinesEvents({ machineId: 'm1', sinceSeq: 3 })).resolves.toEqual({ items: [] })
expect(invoke.mock.calls).toEqual([
- ['remote', { method: 'GET /api/tauri/ssh/machines', payload: null }],
- ['remote', { method: 'GET /api/tauri/ssh/machines/events', payload: { machineId: 'm1', sinceSeq: 3 } }],
+ ['remote', { method: 'GET /api/tauri/remote/machines', payload: null }],
+ ['remote', { method: 'GET /api/tauri/remote/machines/events', payload: { machineId: 'm1', sinceSeq: 3 } }],
])
})
@@ -22,7 +22,7 @@ describe('generated remote API transport', () => {
invoke.mockRejectedValueOnce('REMOTE_API_MISSING: 405')
await expect(postMachinesConnect({ machineId: 'm1' })).rejects.toBe('REMOTE_API_MISSING: 405')
expect(invoke).toHaveBeenCalledWith('remote', {
- method: 'POST /api/tauri/ssh/machines/connect',
+ method: 'POST /api/tauri/remote/machines/connect',
payload: { machineId: 'm1' },
})
})
diff --git a/src/apis/remote.ts b/src/apis/remote.ts
index 578925fe..2c1b011a 100644
--- a/src/apis/remote.ts
+++ b/src/apis/remote.ts
@@ -10,65 +10,85 @@ import type { FetchOptions } from "./http";
/** @method get */
export function getSettings(options?: FetchOptions) {
- return ofetch<Types.GetApiTauriSshSettingsResponse>("/api/tauri/ssh/settings", { method: "get", ...options });
+ return ofetch<Types.GetApiTauriRemoteSettingsResponse>("/api/tauri/remote/settings", { method: "get", ...options });
}
/** @method post */
-export function postSettings(body: Types.PostApiTauriSshSettingsBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshSettingsResponse>("/api/tauri/ssh/settings", { method: "post", body, ...options });
+export function postSettings(body: Types.PostApiTauriRemoteSettingsBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteSettingsResponse>("/api/tauri/remote/settings", { method: "post", body, ...options });
}
/** @method get */
export function getSessionRole(options?: FetchOptions) {
- return ofetch<Types.GetApiTauriSshSessionRoleResponse>("/api/tauri/ssh/session/role", { method: "get", ...options });
+ return ofetch<Types.GetApiTauriRemoteSessionRoleResponse>("/api/tauri/remote/session/role", { method: "get", ...options });
}
/** @method get */
export function getMachines(options?: FetchOptions) {
- return ofetch<Types.GetApiTauriSshMachinesResponse>("/api/tauri/ssh/machines", { method: "get", ...options });
+ return ofetch<Types.GetApiTauriRemoteMachinesResponse>("/api/tauri/remote/machines", { method: "get", ...options });
}
/** @method post */
-export function postMachines(body: Types.PostApiTauriSshMachinesBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshMachinesResponse>("/api/tauri/ssh/machines", { method: "post", body, ...options });
+export function postMachines(body: Types.PostApiTauriRemoteMachinesBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteMachinesResponse>("/api/tauri/remote/machines", { method: "post", body, ...options });
}
/** @method delete */
-export function deleteMachines(body: Types.DeleteApiTauriSshMachinesBody, options?: FetchOptions) {
- return ofetch<Types.DeleteApiTauriSshMachinesResponse>("/api/tauri/ssh/machines", { method: "delete", body, ...options });
+export function deleteMachines(body: Types.DeleteApiTauriRemoteMachinesBody, options?: FetchOptions) {
+ return ofetch<Types.DeleteApiTauriRemoteMachinesResponse>("/api/tauri/remote/machines", { method: "delete", body, ...options });
}
/** @method post */
-export function postMachinesTest(body: Types.PostApiTauriSshMachinesTestBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshMachinesTestResponse>("/api/tauri/ssh/machines/test", { method: "post", body, ...options });
+export function postMachinesTest(body: Types.PostApiTauriRemoteMachinesTestBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteMachinesTestResponse>("/api/tauri/remote/machines/test", { method: "post", body, ...options });
}
/** @method post */
-export function postMachinesConnect(body: Types.PostApiTauriSshMachinesConnectBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshMachinesConnectResponse>("/api/tauri/ssh/machines/connect", { method: "post", body, ...options });
+export function postMachinesConnect(body: Types.PostApiTauriRemoteMachinesConnectBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteMachinesConnectResponse>("/api/tauri/remote/machines/connect", { method: "post", body, ...options });
}
/** @method post */
-export function postMachinesDisconnect(body: Types.PostApiTauriSshMachinesDisconnectBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshMachinesDisconnectResponse>("/api/tauri/ssh/machines/disconnect", { method: "post", body, ...options });
+export function postMachinesDisconnect(body: Types.PostApiTauriRemoteMachinesDisconnectBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteMachinesDisconnectResponse>("/api/tauri/remote/machines/disconnect", { method: "post", body, ...options });
}
/** @method post */
-export function postMachinesInstall(body: Types.PostApiTauriSshMachinesInstallBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshMachinesInstallResponse>("/api/tauri/ssh/machines/install", { method: "post", body, ...options });
+export function postMachinesInstall(body: Types.PostApiTauriRemoteMachinesInstallBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteMachinesInstallResponse>("/api/tauri/remote/machines/install", { method: "post", body, ...options });
}
/** @method get */
-export function getMachinesEvents(params?: Types.GetApiTauriSshMachinesEventsQuery, options?: FetchOptions) {
- return ofetch<Types.GetApiTauriSshMachinesEventsResponse>("/api/tauri/ssh/machines/events", { method: "get", params, ...options });
+export function getMachinesEvents(params?: Types.GetApiTauriRemoteMachinesEventsQuery, options?: FetchOptions) {
+ return ofetch<Types.GetApiTauriRemoteMachinesEventsResponse>("/api/tauri/remote/machines/events", { method: "get", params, ...options });
}
/** @method get */
export function getSyncPreview(options?: FetchOptions) {
- return ofetch<Types.GetApiTauriSshSyncPreviewResponse>("/api/tauri/ssh/sync/preview", { method: "get", ...options });
+ return ofetch<Types.GetApiTauriRemoteSyncPreviewResponse>("/api/tauri/remote/sync/preview", { method: "get", ...options });
}
/** @method post */
-export function postSyncApply(body: Types.PostApiTauriSshSyncApplyBody, options?: FetchOptions) {
- return ofetch<Types.PostApiTauriSshSyncApplyResponse>("/api/tauri/ssh/sync/apply", { method: "post", body, ...options });
+export function postSyncApply(body: Types.PostApiTauriRemoteSyncApplyBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteSyncApplyResponse>("/api/tauri/remote/sync/apply", { method: "post", body, ...options });
+}
+
+/** @method get */
+export function getAccess(params?: Types.GetApiTauriRemoteAccessQuery, options?: FetchOptions) {
+ return ofetch<Types.GetApiTauriRemoteAccessResponse>("/api/tauri/remote/access", { method: "get", params, ...options });
+}
+
+/** @method post */
+export function postAccess(body: Types.PostApiTauriRemoteAccessBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteAccessResponse>("/api/tauri/remote/access", { method: "post", body, ...options });
+}
+
+/** @method post */
+export function postAccessTunnel(body: Types.PostApiTauriRemoteAccessTunnelBody, options?: FetchOptions) {
+ return ofetch<Types.PostApiTauriRemoteAccessTunnelResponse>("/api/tauri/remote/access/tunnel", { method: "post", body, ...options });
+}
+
+/** @method delete */
+export function deleteAccessTunnel(options?: FetchOptions) {
+ return ofetch<Types.DeleteApiTauriRemoteAccessTunnelResponse>("/api/tauri/remote/access/tunnel", { method: "delete", ...options });
}
diff --git a/src/apis/remote.types.ts b/src/apis/remote.types.ts
index 6c01b8a0..68e871c1 100644
--- a/src/apis/remote.types.ts
+++ b/src/apis/remote.types.ts
@@ -1,53 +1,164 @@
-export type GetApiTauriSshSettingsResponse = { enabled?: false | true; error?: string };
-export type PostApiTauriSshSettingsResponse = { enabled?: false | true; error?: string };
-export type GetApiTauriSshSessionRoleResponse = { role?: string; remote?: false | true; origin?: string; error?: string };
-export type GetApiTauriSshMachinesResponse = {
+export type GetApiTauriRemoteSettingsResponse = { enabled?: false | true; error?: string };
+export type PostApiTauriRemoteSettingsResponse = { enabled?: false | true; error?: string };
+export type GetApiTauriRemoteSessionRoleResponse = { role?: string; remote?: false | true; origin?: string; error?: string };
+export type GetApiTauriRemoteMachinesResponse = {
enabled?: false | true;
items?: { id?: string; name?: string; host?: string; port?: number; user?: string; hasPassword?: false | true; hasPassphrase?: false | true; remotePort?: number; profileName?: string; startCommand?: string; color?: string; tintBorder?: false | true; state?: "disconnected" | "testing" | "connecting" | "connected" | "reconnecting" | "given-up"; tunnelBaseUrl?: string; lastError?: string; dshMissing?: false | true; progress?: { phase: "handshake" | "starting" | "probing" | "installing" | "syncing"; attempt?: number; total?: number; item?: string; log?: string }; nextRetryAt?: number; authMethod?: "agent" | "key" | "password" }[];
discovered?: { id?: string; name?: string; host?: string; port?: number; user?: string; hasPassword?: false | true; hasPassphrase?: false | true; remotePort?: number; profileName?: string; startCommand?: string; color?: string; tintBorder?: false | true; state?: "disconnected" | "testing" | "connecting" | "connected" | "reconnecting" | "given-up"; tunnelBaseUrl?: string; lastError?: string; dshMissing?: false | true; progress?: { phase: "handshake" | "starting" | "probing" | "installing" | "syncing"; attempt?: number; total?: number; item?: string; log?: string }; nextRetryAt?: number; authMethod?: "agent" | "key" | "password" }[];
error?: string;
};
-export type PostApiTauriSshMachinesResponse = { error?: string };
-export type DeleteApiTauriSshMachinesResponse = { error?: string };
-export type PostApiTauriSshMachinesTestResponse = { ok?: false | true; banner?: string; message?: string; error?: string };
-export type PostApiTauriSshMachinesConnectResponse = { tunnelBaseUrl?: string; error?: string };
-export type PostApiTauriSshMachinesDisconnectResponse = { error?: string };
-export type PostApiTauriSshMachinesInstallResponse = { installed?: string[]; dshRef?: string; dshVersion?: string; dshPath?: string; credentialsCopied?: false | true; credentialsError?: string; error?: string };
-export type GetApiTauriSshMachinesEventsResponse = { items?: { seq?: number; ts?: string; machineId?: string; stage?: string; line?: string; terminal?: string; reason?: string }[]; nextSeq?: number; error?: string };
-export type GetApiTauriSshMachinesEventsQueryMachineId = string;
-export type GetApiTauriSshMachinesEventsQuerySinceSeq = number;
-export type GetApiTauriSshSyncPreviewResponse = { plugins?: { name?: string; spec?: string; syncable?: false | true; reason?: string }[]; skills?: { name?: string; root?: string }[]; error?: string };
-export type PostApiTauriSshSyncApplyResponse = { items?: { kind?: string; name?: string; root?: string; ok?: false | true; error?: string; log?: string }[]; error?: string };
+export type PostApiTauriRemoteMachinesResponse = { error?: string };
+export type DeleteApiTauriRemoteMachinesResponse = { error?: string };
+export type PostApiTauriRemoteMachinesTestResponse = { ok?: false | true; banner?: string; message?: string; error?: string };
+export type PostApiTauriRemoteMachinesConnectResponse = { tunnelBaseUrl?: string; error?: string };
+export type PostApiTauriRemoteMachinesDisconnectResponse = { error?: string };
+export type PostApiTauriRemoteMachinesInstallResponse = { installed?: string[]; dshRef?: string; dshVersion?: string; dshPath?: string; credentialsCopied?: false | true; credentialsError?: string; error?: string };
+export type GetApiTauriRemoteMachinesEventsResponse = { items?: { seq?: number; ts?: string; machineId?: string; stage?: string; line?: string; terminal?: string; reason?: string }[]; nextSeq?: number; error?: string };
+export type GetApiTauriRemoteMachinesEventsQueryMachineId = string;
+export type GetApiTauriRemoteMachinesEventsQuerySinceSeq = number;
+export type GetApiTauriRemoteSyncPreviewResponse = { plugins?: { name?: string; spec?: string; syncable?: false | true; reason?: string }[]; skills?: { name?: string; root?: string }[]; error?: string };
+export type PostApiTauriRemoteSyncApplyResponse = { items?: { kind?: string; name?: string; root?: string; ok?: false | true; error?: string; log?: string }[]; error?: string };
+export type GetApiTauriRemoteAccessResponse = {
+ version: number;
+ enabled: false | true;
+ state: "error" | "stopped" | "listening";
+ listening: false | true;
+ listen: { address: string; port: number };
+ port: number;
+ auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };
+ addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];
+ recommended?: string;
+ link?: string;
+ maskLink?: string;
+ qr?: string;
+ linkSource?: "loopback" | "lan";
+ pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };
+ generatedPassword?: string;
+ tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };
+ localPort?: number;
+ error?: string;
+ warnings?: string[];
+ events: { seq: number; ts: string; kind: "auth" | "token" | "state"; line: string }[];
+};
+export type GetApiTauriRemoteAccessQuerySincePairingUseSeq = number;
+export type PostApiTauriRemoteAccessResponse =
+ | {
+ version: number;
+ enabled: false | true;
+ state: "error" | "stopped" | "listening";
+ listening: false | true;
+ listen: { address: string; port: number };
+ port: number;
+ auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };
+ addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];
+ recommended?: string;
+ link?: string;
+ maskLink?: string;
+ qr?: string;
+ linkSource?: "loopback" | "lan";
+ pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };
+ generatedPassword?: string;
+ tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };
+ localPort?: number;
+ error?: string;
+ warnings?: string[];
+ events: { seq: number; ts: string; kind: "auth" | "token" | "state"; line: string }[];
+ }
+ | { error: string };
+export type PostApiTauriRemoteAccessTunnelResponse =
+ | {
+ version: number;
+ enabled: false | true;
+ state: "error" | "stopped" | "listening";
+ listening: false | true;
+ listen: { address: string; port: number };
+ port: number;
+ auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };
+ addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];
+ recommended?: string;
+ link?: string;
+ maskLink?: string;
+ qr?: string;
+ linkSource?: "loopback" | "lan";
+ pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };
+ generatedPassword?: string;
+ tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };
+ localPort?: number;
+ error?: string;
+ warnings?: string[];
+ events: { seq: number; ts: string; kind: "auth" | "token" | "state"; line: string }[];
+ }
+ | { error: string };
+export type DeleteApiTauriRemoteAccessTunnelResponse =
+ | {
+ version: number;
+ enabled: false | true;
+ state: "error" | "stopped" | "listening";
+ listening: false | true;
+ listen: { address: string; port: number };
+ port: number;
+ auth: { enabled: false | true; scope: "public_only" | "all"; hasPassword?: false | true; hasToken?: false | true; token?: string };
+ addresses: { address: string; family: "ipv4" | "ipv6"; interface: string; scope: "loopback" | "private" | "public" | "link-local"; score: number; recommended: false | true }[];
+ recommended?: string;
+ link?: string;
+ maskLink?: string;
+ qr?: string;
+ linkSource?: "loopback" | "lan";
+ pairing?: { code: string; expiresAt: number; usedSeq: number; link?: string; qr?: string; tunnelLink?: string; tunnelQr?: string };
+ generatedPassword?: string;
+ tunnel?: { state: "error" | "starting" | "stopped" | "running"; events: { seq: number; ts: string; kind: "state" | "process" | "progress"; line: string }[]; token?: string; url?: string; port?: number; link?: string; qr?: string; progress?: { stage: "ready" | "spawn" | "download" | "verify" | "check" | "extract" | "domain"; url?: string; received?: number; total?: number }; error?: string; mode: "quick" | "token"; enabled: false | true; hostname: null | string };
+ localPort?: number;
+ error?: string;
+ warnings?: string[];
+ events: { seq: number; ts: string; kind: "auth" | "token" | "state"; line: string }[];
+ }
+ | { error: string };
-export interface PostApiTauriSshSettingsBody {
+export interface PostApiTauriRemoteSettingsBody {
enabled?: false | true;
}
-export interface PostApiTauriSshMachinesBody {
+export interface PostApiTauriRemoteMachinesBody {
machineId?: string;
row?: { name?: string; host?: string; port?: number; user?: string; remotePort?: number; profileName?: string; startCommand?: string; color?: string; tintBorder?: false | true };
secrets?: { password?: string; passphrase?: string };
}
-export interface DeleteApiTauriSshMachinesBody {
+export interface DeleteApiTauriRemoteMachinesBody {
machineId?: string;
}
-export interface PostApiTauriSshMachinesTestBody {
+export interface PostApiTauriRemoteMachinesTestBody {
machineId?: string;
}
-export interface PostApiTauriSshMachinesConnectBody {
+export interface PostApiTauriRemoteMachinesConnectBody {
machineId?: string;
}
-export interface PostApiTauriSshMachinesDisconnectBody {
+export interface PostApiTauriRemoteMachinesDisconnectBody {
machineId?: string;
}
-export interface PostApiTauriSshMachinesInstallBody {
+export interface PostApiTauriRemoteMachinesInstallBody {
machineId?: string;
}
-export interface PostApiTauriSshSyncApplyBody {
+export interface PostApiTauriRemoteSyncApplyBody {
machineId?: string;
plugins?: { name?: string; spec?: string }[];
skills?: { name?: string; root?: string }[];
}
-export interface GetApiTauriSshMachinesEventsQuery {
- machineId?: GetApiTauriSshMachinesEventsQueryMachineId;
- sinceSeq?: GetApiTauriSshMachinesEventsQuerySinceSeq;
+export interface PostApiTauriRemoteAccessBody {
+ enabled?: false | true;
+ address?: string;
+ port?: number;
+ authEnabled?: false | true;
+ scope?: "public_only" | "all";
+ password?: null | string;
+}
+export interface PostApiTauriRemoteAccessTunnelBody {
+ mode?: "quick" | "token";
+ token?: string;
+ hostname?: string;
+}
+export interface GetApiTauriRemoteMachinesEventsQuery {
+ machineId?: GetApiTauriRemoteMachinesEventsQueryMachineId;
+ sinceSeq?: GetApiTauriRemoteMachinesEventsQuerySinceSeq;
+}
+export interface GetApiTauriRemoteAccessQuery {
+ sincePairingUseSeq?: GetApiTauriRemoteAccessQuerySincePairingUseSeq;
}
diff --git a/src/hooks/use-remote.logic.test.ts b/src/hooks/use-remote.logic.test.ts
index 5bc19ffc..362ae6c3 100644
--- a/src/hooks/use-remote.logic.test.ts
+++ b/src/hooks/use-remote.logic.test.ts
@@ -1,8 +1,8 @@
-import type { SshMachineRow } from './use-remote'
+import type { RemoteMachineRow } from './use-remote'
import { describe, expect, it } from 'vitest'
import { dotClassOf, reconcileSwitcher } from './use-remote'
-function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {
+function machineOf(partial: Partial<RemoteMachineRow>): RemoteMachineRow {
return {
id: 'm1',
name: 'machine',
diff --git a/src/hooks/use-remote.test.ts b/src/hooks/use-remote.test.ts
index 03615be5..f4e188f5 100644
--- a/src/hooks/use-remote.test.ts
+++ b/src/hooks/use-remote.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import type { PropsWithChildren } from 'react'
-import type { SshMachineRow } from './use-remote'
+import type { RemoteMachineRow } from './use-remote'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
import { createElement, StrictMode } from 'react'
@@ -13,14 +13,14 @@ vi.mock('@tauri-apps/api/core', () => ({ invoke }))
vi.mock('@tauri-apps/api/window', () => ({ getCurrentWindow: () => windowInfo }))
let client: QueryClient
-let rows: SshMachineRow[]
+let rows: RemoteMachineRow[]
let enabled: boolean
let listError: unknown
let eventItems: { seq: number, line: string }[]
let connect: (id: string) => Promise<{ tunnelBaseUrl: string }>
const disconnect = vi.fn(async (_id: string) => ({}))
-function machineOf(partial: Partial<SshMachineRow> = {}): SshMachineRow {
+function machineOf(partial: Partial<RemoteMachineRow> = {}): RemoteMachineRow {
return { id: 'm1', name: 'alpha', state: 'disconnected', ...partial }
}
@@ -58,15 +58,15 @@ beforeEach(() => {
invoke.mockReset().mockImplementation(async (command: string, args: { method: string, payload: { machineId: string, sinceSeq?: number } }) => {
expect(command).toBe('remote')
switch (args.method) {
- case 'GET /api/tauri/ssh/machines':
+ case 'GET /api/tauri/remote/machines':
if (listError !== undefined)
throw listError
return { enabled, items: rows, discovered: [] }
- case 'GET /api/tauri/ssh/machines/events':
+ case 'GET /api/tauri/remote/machines/events':
return { items: eventItems.filter(item => item.seq >= (args.payload.sinceSeq ?? 0)) }
- case 'POST /api/tauri/ssh/machines/connect':
+ case 'POST /api/tauri/remote/machines/connect':
return connect(args.payload.machineId)
- case 'POST /api/tauri/ssh/machines/disconnect':
+ case 'POST /api/tauri/remote/machines/disconnect':
return disconnect(args.payload.machineId)
default:
throw new Error(`Unexpected method: ${args.method}`)
@@ -138,7 +138,7 @@ describe('useRemote 查询、降级与启动寻址', () => {
await act(async () => {
await vi.advanceTimersByTimeAsync(6000)
})
- const lists = invoke.mock.calls.filter(call => call[1].method === 'GET /api/tauri/ssh/machines')
+ const lists = invoke.mock.calls.filter(call => call[1].method === 'GET /api/tauri/remote/machines')
expect(lists).toHaveLength(4)
unmount()
await act(async () => {
@@ -335,7 +335,7 @@ describe('useRemote 切换和连接进度', () => {
await client.refetchQueries({ queryKey: queryKeys.remoteEvents })
})
await waitFor(() => expect(result.current.connectLog).toEqual(['ssh ok', 'download', 'started']))
- expect(invoke).toHaveBeenCalledWith('remote', { method: 'GET /api/tauri/ssh/machines/events', payload: { machineId: 'm1', sinceSeq: 2 } })
+ expect(invoke).toHaveBeenCalledWith('remote', { method: 'GET /api/tauri/remote/machines/events', payload: { machineId: 'm1', sinceSeq: 2 } })
rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
await act(async () => {
release({ tunnelBaseUrl: 'http://127.0.0.1:4001' })
diff --git a/src/hooks/use-remote.ts b/src/hooks/use-remote.ts
index 56d19927..d21ce4c8 100644
--- a/src/hooks/use-remote.ts
+++ b/src/hooks/use-remote.ts
@@ -1,4 +1,4 @@
-import type { GetApiTauriSshMachinesResponse } from '@/apis/remote.types'
+import type { GetApiTauriRemoteMachinesResponse } from '@/apis/remote.types'
import { useEventListener, useUnmount, useWatch } from '@reause/core'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { getCurrentWindow } from '@tauri-apps/api/window'
@@ -6,12 +6,12 @@ import { useRef, useState } from 'react'
import { getMachines, getMachinesEvents, postMachinesConnect, postMachinesDisconnect } from '@/apis/remote'
import { queryKeys } from '@/config/query-keys'
-type SshMachineListItem = NonNullable<GetApiTauriSshMachinesResponse['items']>[number]
-type SshConnectionState = NonNullable<SshMachineListItem['state']>
-type SshProgress = NonNullable<SshMachineListItem['progress']>
-type SshProgressPhase = SshProgress['phase']
+type RemoteMachineListItem = NonNullable<GetApiTauriRemoteMachinesResponse['items']>[number]
+type RemoteConnectionState = NonNullable<RemoteMachineListItem['state']>
+type RemoteProgress = NonNullable<RemoteMachineListItem['progress']>
+type RemoteProgressPhase = RemoteProgress['phase']
-export type SshMachineRow = { id: string, name: string, state: SshConnectionState } & Pick<SshMachineListItem, 'color' | 'tintBorder' | 'host' | 'port' | 'user' | 'tunnelBaseUrl' | 'lastError' | 'nextRetryAt' | 'authMethod'> & { progress?: Pick<SshProgress, 'phase'> }
+export type RemoteMachineRow = { id: string, name: string, state: RemoteConnectionState } & Pick<RemoteMachineListItem, 'color' | 'tintBorder' | 'host' | 'port' | 'user' | 'tunnelBaseUrl' | 'lastError' | 'nextRetryAt' | 'authMethod'> & { progress?: Pick<RemoteProgress, 'phase'> }
interface SwitcherTargets {
activeId: string | null
@@ -30,7 +30,7 @@ export function useRemote() {
const queryClient = useQueryClient()
const [targets, setTargets] = useState<SwitcherTargets>({ activeId: null, pendingId: null, activeTunnelUrl: '' })
const [bootId, setBootId] = useState(initialMachineId)
- const [connectTrail, setConnectTrail] = useState<SshProgressPhase[]>([])
+ const [connectTrail, setConnectTrail] = useState<RemoteProgressPhase[]>([])
const [connectDismissed, setConnectDismissed] = useState(false)
const [attempt, setAttempt] = useState(0)
const epochRef = useRef(0)
@@ -43,7 +43,7 @@ export function useRemote() {
}
catch (error) {
if (String(error).startsWith('REMOTE_API_MISSING:'))
- return { enabled: false, machines: [] as SshMachineRow[] }
+ return { enabled: false, machines: [] as RemoteMachineRow[] }
throw error
}
},
@@ -205,7 +205,7 @@ export function useRemote() {
export type Remote = ReturnType<typeof useRemote>
-export function dotClassOf(machine: Pick<SshMachineRow, 'color' | 'state'>): string {
+export function dotClassOf(machine: Pick<RemoteMachineRow, 'color' | 'state'>): string {
if (machine.color !== undefined)
return ''
switch (machine.state) {
@@ -222,7 +222,7 @@ export function dotClassOf(machine: Pick<SshMachineRow, 'color' | 'state'>): str
}
}
-export function reconcileSwitcher(prev: SwitcherTargets, machines: readonly SshMachineRow[]): SwitcherTargets {
+export function reconcileSwitcher(prev: SwitcherTargets, machines: readonly RemoteMachineRow[]): SwitcherTargets {
let { activeId, pendingId, activeTunnelUrl } = prev
const active = machines.find(machine => machine.id === activeId)
if (active === undefined || active.state === 'disconnected' || active.state === 'given-up') {
@@ -244,10 +244,10 @@ export function reconcileSwitcher(prev: SwitcherTargets, machines: readonly SshM
return { activeId, pendingId, activeTunnelUrl }
}
-export function machineRowsOf(value?: { enabled?: boolean, items?: readonly unknown[], discovered?: readonly unknown[] }): { enabled: boolean, machines: SshMachineRow[] } {
+export function machineRowsOf(value?: { enabled?: boolean, items?: readonly unknown[], discovered?: readonly unknown[] }): { enabled: boolean, machines: RemoteMachineRow[] } {
const machines = [...(value?.items ?? []), ...(value?.discovered ?? [])]
.map(machineRowOf)
- .filter((row): row is SshMachineRow => row !== undefined)
+ .filter((row): row is RemoteMachineRow => row !== undefined)
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
return { enabled: value?.enabled === true, machines }
}
@@ -263,7 +263,7 @@ export function eventEntriesOf(value?: { items?: readonly unknown[] }): { seq: n
})
}
-function machineRowOf(raw: unknown): SshMachineRow | undefined {
+function machineRowOf(raw: unknown): RemoteMachineRow | undefined {
if (typeof raw !== 'object' || raw === null)
return undefined
const value = raw as Record<string, unknown>
@@ -279,7 +279,7 @@ function machineRowOf(raw: unknown): SshMachineRow | undefined {
...typeof value.host === 'string' && value.host !== '' ? { host: value.host } : {},
...typeof value.port === 'number' ? { port: value.port } : {},
...typeof value.user === 'string' && value.user !== '' ? { user: value.user } : {},
- state: value.state as SshConnectionState,
+ state: value.state as RemoteConnectionState,
...typeof value.tunnelBaseUrl === 'string' ? { tunnelBaseUrl: value.tunnelBaseUrl } : {},
...typeof value.lastError === 'string' ? { lastError: value.lastError } : {},
...typeof value.nextRetryAt === 'number' ? { nextRetryAt: value.nextRetryAt } : {},
@@ -288,11 +288,11 @@ function machineRowOf(raw: unknown): SshMachineRow | undefined {
}
}
-function progressOf(raw: unknown): { progress?: Pick<SshProgress, 'phase'> } {
+function progressOf(raw: unknown): { progress?: Pick<RemoteProgress, 'phase'> } {
if (typeof raw !== 'object' || raw === null)
return {}
const value = raw as Record<string, unknown>
if (!['handshake', 'installing', 'starting', 'probing', 'syncing'].includes(String(value.phase)))
return {}
- return { progress: { phase: value.phase as SshProgressPhase } }
+ return { progress: { phase: value.phase as RemoteProgressPhase } }
}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index e64e802e..1183e0cf 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -584,6 +584,40 @@
"remote.connect.cancel": "Cancel",
"buttons.close": "Close",
"remote.loading": "Loading remote interface…",
+ "remote.share": "Share",
+ "remote.share.settings": "Open remote access settings",
+ "remote.share.mobile": "DSH Mobile",
+ "remote.share.mobile_hint": "Connect to your computer and use DSH from your phone.",
+ "remote.share.copied": "Link copied",
+ "remote.share.action_failed": "Remote access action failed",
+ "remote.share.tab_lan": "LAN",
+ "remote.share.tab_tunnel": "Public tunnel",
+ "remote.share.loading": "Reading share status…",
+ "remote.share.lan_off_desc": "LAN sharing is off — devices on the same network cannot connect.",
+ "remote.share.lan_enable": "Enable LAN sharing",
+ "remote.share.lan_local_only": "Only a loopback address is bound, so the link works on this machine alone. Switch to a LAN address in Settings before sharing.",
+ "remote.share.qr_alt": "Share QR code",
+ "remote.share.copy": "Copy link",
+ "remote.share.tunnel_off_desc": "Public tunnel is off — devices outside this network cannot connect.",
+ "remote.share.tunnel_enable": "Enable tunnel",
+ "remote.share.tunnel_starting": "Starting tunnel…",
+ "remote.share.stage.check": "Checking environment",
+ "remote.share.stage.download": "Downloading tunnel binary",
+ "remote.share.stage.extract": "Extracting",
+ "remote.share.stage.verify": "Verifying",
+ "remote.share.stage.spawn": "Starting process",
+ "remote.share.stage.domain": "Assigning domain",
+ "remote.share.stage.ready": "Ready",
+ "remote.share.download_progress": "{{received}} / {{total}} MB",
+ "remote.share.tunnel_stop": "Stop tunnel",
+ "remote.share.tunnel_failed": "Tunnel failed to start",
+ "remote.share.pairing": "Temporary pairing code",
+ "remote.share.pairing_absent": "The host did not provide a pairing code.",
+ "remote.share.pairing_expires": "Expires in {{time}}",
+ "remote.share.pairing_hint": "Enter the code on the other device; valid for 5 minutes.",
+ "remote.share.password": "Access password generated just now",
+ "remote.share.password_hint": "The plaintext appears only here and cannot be retrieved later; copy it before closing.",
+ "remote.share.password_dismiss": "Saved it",
"config.appearance": "Appearance",
"appearance.description": "Device-local desktop colours, text scale, and layout. These settings are not synced to other Harness clients.",
"appearance.palette": "Colour palette",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 85c93929..976159cd 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -584,6 +584,40 @@
"remote.connect.cancel": "取消连接",
"buttons.close": "关闭",
"remote.loading": "正在加载远端界面…",
+ "remote.share": "远程",
+ "remote.share.settings": "打开远程访问设置",
+ "remote.share.mobile": "DSH Mobile",
+ "remote.share.mobile_hint": "在手机上连接并使用电脑上的 DSH。",
+ "remote.share.copied": "链接已复制",
+ "remote.share.action_failed": "远程访问操作失败",
+ "remote.share.tab_lan": "局域网",
+ "remote.share.tab_tunnel": "公网隧道",
+ "remote.share.loading": "正在读取分享状态…",
+ "remote.share.lan_off_desc": "局域网分享未开启,同一网络下的设备无法访问。",
+ "remote.share.lan_enable": "开启局域网分享",
+ "remote.share.lan_local_only": "当前只绑定了回环地址,链接仅本机可用。请先在设置里改为局域网地址再分享。",
+ "remote.share.qr_alt": "分享二维码",
+ "remote.share.copy": "复制链接",
+ "remote.share.tunnel_off_desc": "公网隧道未开启,外网设备无法访问。",
+ "remote.share.tunnel_enable": "启用隧道",
+ "remote.share.tunnel_starting": "正在启动隧道",
+ "remote.share.stage.check": "检查环境",
+ "remote.share.stage.download": "下载隧道程序",
+ "remote.share.stage.extract": "解压",
+ "remote.share.stage.verify": "校验",
+ "remote.share.stage.spawn": "启动进程",
+ "remote.share.stage.domain": "分配域名",
+ "remote.share.stage.ready": "就绪",
+ "remote.share.download_progress": "{{received}} / {{total}} MB",
+ "remote.share.tunnel_stop": "停止隧道",
+ "remote.share.tunnel_failed": "隧道启动失败",
+ "remote.share.pairing": "临时配对码",
+ "remote.share.pairing_absent": "宿主暂未提供配对码。",
+ "remote.share.pairing_expires": "{{time}} 后过期",
+ "remote.share.pairing_hint": "设备输入配对连接,5 分钟内有效。",
+ "remote.share.password": "本次自动生成的访问密码",
+ "remote.share.password_hint": "明文只在本次出现,关闭后无法再取回;请先复制保存。",
+ "remote.share.password_dismiss": "我已保存",
"config.appearance": "外观",
"appearance.description": "仅保存在本机的桌面配色、字号与布局,不会同步到其他 Harness 客户端。",
"appearance.palette": "配色方案",
diff --git a/src/layout/components/nav-bridge.test.ts b/src/layout/components/nav-bridge.test.ts
index 6e35d0f6..15453e68 100644
--- a/src/layout/components/nav-bridge.test.ts
+++ b/src/layout/components/nav-bridge.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { navBridgeOf, SSH_SECTION, SSH_TAB_MACHINES, SSH_TAB_SYNC } from './nav-bridge'
+import { navBridgeOf, REMOTE_SECTION, REMOTE_TAB_MACHINES, REMOTE_TAB_SYNC } from './nav-bridge'
describe('navBridgeOf', () => {
it('sends no callbacks while the iframe is absent', () => {
@@ -22,8 +22,8 @@ describe('navBridgeOf', () => {
{ type: 'dsh://session:new' },
{ type: 'dsh://workspace:add' },
// 机器管理与同步同属 SSH 分区,靠 tab 落到对应标签页
- { type: 'dsh://settings:open', section: SSH_SECTION, tab: SSH_TAB_MACHINES },
- { type: 'dsh://settings:open', section: SSH_SECTION, tab: SSH_TAB_SYNC },
+ { type: 'dsh://settings:open', section: REMOTE_SECTION, tab: REMOTE_TAB_MACHINES },
+ { type: 'dsh://settings:open', section: REMOTE_SECTION, tab: REMOTE_TAB_SYNC },
])
})
})
diff --git a/src/layout/components/nav-bridge.ts b/src/layout/components/nav-bridge.ts
index 1349201e..495d593c 100644
--- a/src/layout/components/nav-bridge.ts
+++ b/src/layout/components/nav-bridge.ts
@@ -1,14 +1,17 @@
import type { NavbarProps } from './navbar'
import type { IframeOutboundMessage } from '@/hooks/use-iframe-post'
-/** 设置浮层分区 id:SSH(dsh-tauri-ssh 插件注册的唯一分区,内部再用 Tabs 分页)。 */
-export const SSH_SECTION = 'dsh-tauri-ssh'
+/** 设置浮层分区 id:SSH(dsh-tauri-remote 插件注册的唯一分区,内部再用 Tabs 分页)。 */
+export const REMOTE_SECTION = 'dsh-tauri-remote'
-/** SSH 分区内的标签页 id(与插件 `SSH_TAB_*` 约定一致)。 */
-export const SSH_TAB_MACHINES = 'machines'
+/** SSH 分区内的标签页 id(与插件 `REMOTE_TAB_*` 约定一致)。 */
+export const REMOTE_TAB_MACHINES = 'machines'
/** 同步到远端标签页 id。 */
-export const SSH_TAB_SYNC = 'sync'
+export const REMOTE_TAB_SYNC = 'sync'
+
+/** 本机访问(入站暴露与公网隧道)标签页 id。 */
+export const REMOTE_TAB_ACCESS = 'access'
/**
* 导航栏回调桥:把每个导航栏动作翻译成一条宿主 → iframe 协议消息。
@@ -29,7 +32,7 @@ export function navBridgeOf(post: (message: IframeOutboundMessage) => void, live
onNewChat: () => post({ type: 'dsh://session:new' }),
onOpenFolder: () => post({ type: 'dsh://workspace:add' }),
// 机器管理与同步同属 SSH 分区:分区相同,靠 tab 字段落到对应标签页
- onOpenMachineManager: () => post({ type: 'dsh://settings:open', section: SSH_SECTION, tab: SSH_TAB_MACHINES }),
- onOpenSyncToRemote: () => post({ type: 'dsh://settings:open', section: SSH_SECTION, tab: SSH_TAB_SYNC }),
+ onOpenMachineManager: () => post({ type: 'dsh://settings:open', section: REMOTE_SECTION, tab: REMOTE_TAB_MACHINES }),
+ onOpenSyncToRemote: () => post({ type: 'dsh://settings:open', section: REMOTE_SECTION, tab: REMOTE_TAB_SYNC }),
}
}
diff --git a/src/layout/components/navbar.tsx b/src/layout/components/navbar.tsx
index 9735f448..75b42a8e 100644
--- a/src/layout/components/navbar.tsx
+++ b/src/layout/components/navbar.tsx
@@ -32,12 +32,13 @@ import { TaskManagerDialog } from '@/ui/dialog/task-manager'
import { DesktopUpdateDialog } from '@/ui/dialog/update'
import { writeClipboardText } from '@/utils/clipboard'
import { toast } from '@/utils/toast'
+import { RemoteShare } from './remote-share'
import { RemoteSwitcher } from './remote-switcher'
/**
* 壳层窗口顶部导航栏(44px,常驻):
*
- * [侧边栏(展开/收起)] [文件][运行][帮助][更新可用] [ 空白拖拽区 ] [本地/远端] [最小化][最大化][后台化(X)]
+ * [侧边栏(展开/收起)] [文件][运行][帮助][更新可用] [ 空白拖拽区 ] [远程][本地/远端] [最小化][最大化][后台化(X)]
*
* - 侧边栏:经 postMessage 操控 iframe 内的 dsh 应用
* (`dsh://sidebar:toggle`,由 dsh-tauri 插件的 `client/register/sidebar.ts`
@@ -47,7 +48,9 @@ import { RemoteSwitcher } from './remote-switcher'
* 左侧控件只在「dsh-tauri 插件已启用(已安装)」且传入 `onToggleSidebar` 时渲染,
* 原生桥缺席时控件没有可靠接收方,避免出现点了没反应的死按钮。
* - 本地 / 远端:`RemoteSwitcher` 固定在右侧,SSH 功能未启用时
- * 自身不渲染(见 `remote-switcher.tsx`);macOS 上其左侧是「更新可用」chip。
+ * 自身不渲染(见 `remote-switcher.tsx`)。
+ * - 远程:`RemoteShare` 紧邻切换器左侧,入站分享(局域网 / 公网隧道)与 SSH 开关无关,
+ * 与切换器共用服务可用门槛(见 `remote-share.tsx`);齿轮入口经 `onOpenRemoteAccess` 定位到本机访问页。
* - 文件:新建窗口(Tauri 再开一个 webview)/ 新聊天、打开文件夹(经协议调用 dsh 官方
* 「新建会话」「添加工作区」,接收方是 dsh-tauri 的 `client/register/navigation.ts`)/
* 关闭(隐藏到托盘)/ 退出(完整退出)。两条依赖 iframe 的项在回调缺席时禁用。
@@ -237,6 +240,8 @@ export interface NavbarProps {
onOpenMachineManager?: () => void
/** 同步到远端:向 iframe 发 `dsh://settings:open` 定位同步分区(与机器管理同级) */
onOpenSyncToRemote?: () => void
+ /** 本机访问:远程分享弹层的齿轮入口,向 iframe 发 `dsh://settings:open` 定位远程插件的「远程访问」分区 */
+ onOpenRemoteAccess?: () => void
/** 打开文件夹:向 iframe 发 `dsh://workspace:add`(dsh 官方「添加工作区」);传入时该项可用 */
onOpenFolder?: () => void
/** 显示键盘快捷键:向 iframe 发 `dsh://shortcuts:open`,弹官方 `shortcuts.open` 弹层(官方蒙版);传入时该项可用 */
@@ -244,7 +249,7 @@ export interface NavbarProps {
onViewCommand?: (command: DshViewCommand) => void
}
-export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSidebar, onNewChat, onOpenFolder, onOpenShortcuts, onViewCommand, onOpenMachineManager, onOpenSyncToRemote }: NavbarProps) {
+export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSidebar, onNewChat, onOpenFolder, onOpenShortcuts, onViewCommand, onOpenMachineManager, onOpenSyncToRemote, onOpenRemoteAccess }: NavbarProps) {
const { t } = useTranslation()
const queryClient = useQueryClient()
const isFullscreen = useMacOSFullscreen()
@@ -842,8 +847,11 @@ export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSideb
同参数的 `background` / `backdrop-filter` 过渡(见 `getOverlayMarkedStyle`)。 */}
<div className="absolute" style={dshStyle.marked || {}} />
- {/* 「本地」/ 远端机器切换器:SSH 功能启用后才出现(未启用时组件自身不渲染),
- 固定在右侧,与左侧的文件/运行/帮助菜单分列两端(macOS 上左侧是「更新可用」chip)。 */}
+ {/* 右侧控件:入站分享(远程)排在本地/远端切换器之前;切换器在 SSH 未启用时自身不渲染。 */}
+ <If cond={onToggleSidebar != null}>
+ <RemoteShare onManage={onOpenRemoteAccess} />
+ </If>
+
<RemoteSwitcher onChange={onRemoteChange} visible={onToggleSidebar != null} onManage={onOpenMachineManager} onSync={onOpenSyncToRemote} />
<If cond={!IS_MACOS}>
diff --git a/src/layout/components/remote-share.test.tsx b/src/layout/components/remote-share.test.tsx
new file mode 100644
index 00000000..3d44564e
--- /dev/null
+++ b/src/layout/components/remote-share.test.tsx
@@ -0,0 +1,531 @@
+// @vitest-environment jsdom
+import { clearMocks, mockIPC } from '@tauri-apps/api/mocks'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { RemoteShare } from './remote-share'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+const getAccessSpy = vi.fn<(params?: { sincePairingUseSeq?: number }) => Promise<unknown>>()
+const postAccessSpy = vi.fn<(body: unknown) => Promise<unknown>>()
+const postAccessTunnelSpy = vi.fn<(body: unknown) => Promise<unknown>>()
+const deleteAccessTunnelSpy = vi.fn<() => Promise<unknown>>()
+vi.mock('@/apis/remote', () => ({
+ getAccess: (params?: { sincePairingUseSeq?: number }) => getAccessSpy(params),
+ postAccess: (body: unknown) => postAccessSpy(body),
+ postAccessTunnel: (body: unknown) => postAccessTunnelSpy(body),
+ deleteAccessTunnel: () => deleteAccessTunnelSpy(),
+}))
+
+const openUrlSpy = vi.fn<(args: { url: string }) => Promise<void>>()
+const clipboardSpy = vi.fn<(text: string, message?: string) => Promise<void>>()
+vi.mock('@/utils/clipboard', () => ({
+ writeClipboardText: (text: string, message?: string) => clipboardSpy(text, message),
+}))
+
+vi.stubGlobal('ResizeObserver', class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+})
+
+if (typeof CSS === 'undefined')
+ vi.stubGlobal('CSS', { escape: (value: string) => value })
+
+Element.prototype.getAnimations = function () {
+ return []
+}
+
+const QR = 'data:image/png;base64,qr'
+const PAIR_CODE = '482913'
+const LAN_LINK = 'http://192.168.1.5:3080/?auth=482913'
+const TUNNEL_LINK = 'https://demo.trycloudflare.com/?auth=482913'
+
+function pairingOf(patch: Record<string, unknown> = {}) {
+ return {
+ code: PAIR_CODE,
+ expiresAt: Date.now() + 300_000,
+ link: LAN_LINK,
+ qr: QR,
+ ...patch,
+ }
+}
+
+function statusOf(patch: Record<string, unknown> = {}) {
+ return {
+ version: 1,
+ enabled: true,
+ state: 'stopped',
+ listening: false,
+ listen: { address: '0.0.0.0', port: 3080 },
+ port: 3080,
+ linkSource: 'lan',
+ tunnel: { enabled: false, mode: 'quick', hostname: null, state: 'stopped', events: [] },
+ ...patch,
+ }
+}
+
+const listening = {
+ state: 'listening',
+ listening: true,
+ link: LAN_LINK,
+ maskLink: 'http://192.168.1.5:3080/?auth=***',
+ qr: QR,
+ pairing: pairingOf(),
+}
+
+async function openShare() {
+ fireEvent.click(screen.getByRole('button', { name: 'remote.share' }))
+ await screen.findByRole('dialog')
+}
+
+function clickTunnelTab() {
+ fireEvent.click(screen.getByText('remote.share.tab_tunnel'))
+}
+
+beforeEach(() => {
+ openUrlSpy.mockReset().mockResolvedValue(undefined)
+ mockIPC((command, args) => {
+ if (command === 'open_external_url')
+ return openUrlSpy(args as { url: string })
+ throw new Error(`Unexpected native command: ${command}`)
+ })
+ getAccessSpy.mockReset()
+ postAccessSpy.mockReset()
+ postAccessTunnelSpy.mockReset()
+ deleteAccessTunnelSpy.mockReset()
+ clipboardSpy.mockReset()
+ clipboardSpy.mockResolvedValue(undefined)
+ getAccessSpy.mockResolvedValue(statusOf())
+ postAccessSpy.mockResolvedValue(statusOf(listening))
+ postAccessTunnelSpy.mockResolvedValue(statusOf())
+ deleteAccessTunnelSpy.mockResolvedValue(statusOf())
+})
+
+afterEach(() => {
+ cleanup()
+ clearMocks()
+ vi.restoreAllMocks()
+ vi.useRealTimers()
+})
+
+function consumedStatus(usedSeq: number, code = '735026') {
+ return statusOf({ ...listening, pairing: pairingOf({ usedSeq, code, link: `http://192.168.1.5:3080/?auth=${code}` }) })
+}
+
+function mockPairingWatch(usedSeq = 0) {
+ let current = consumedStatus(usedSeq, PAIR_CODE)
+ const polls: ReturnType<typeof Promise.withResolvers<unknown>>[] = []
+ getAccessSpy.mockImplementation((params) => {
+ if (params?.sincePairingUseSeq !== undefined) {
+ const poll = Promise.withResolvers<unknown>()
+ polls.push(poll)
+ return poll.promise
+ }
+ return Promise.resolve({ ...current })
+ })
+ return {
+ polls,
+ update(next: ReturnType<typeof statusOf>) {
+ current = next
+ },
+ }
+}
+
+function closeShare() {
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
+}
+
+describe('remoteShare 临时码消费订阅', () => {
+ it('显示消费基线后立即长轮询,使用响应到达即关闭,重开显示新码并订阅新基线', async () => {
+ const watch = mockPairingWatch()
+ render(<RemoteShare />)
+ await openShare()
+ expect((await screen.findByTestId('remote-share-pairing')).textContent).toBe(PAIR_CODE)
+ await waitFor(() => expect(getAccessSpy).toHaveBeenCalledWith({ sincePairingUseSeq: 0 }))
+ expect(watch.polls).toHaveLength(1)
+
+ const next = consumedStatus(1)
+ watch.update(next)
+ await act(async () => watch.polls[0]!.resolve(next))
+
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ expect(getAccessSpy).toHaveBeenCalledTimes(2)
+ await openShare()
+ expect((await screen.findByTestId('remote-share-pairing')).textContent).toBe('735026')
+ await waitFor(() => expect(getAccessSpy).toHaveBeenCalledWith({ sincePairingUseSeq: 1 }))
+ expect(screen.getByRole('dialog')).not.toBeNull()
+ expect(watch.polls).toHaveLength(2)
+ })
+
+ it('同一消费序号的超时响应继续订阅,TTL 换码不关闭', async () => {
+ const watch = mockPairingWatch(4)
+ render(<RemoteShare />)
+ await openShare()
+ await waitFor(() => expect(watch.polls).toHaveLength(1))
+ const renewed = consumedStatus(4)
+ watch.update(renewed)
+ await act(async () => watch.polls[0]!.resolve(renewed))
+
+ await waitFor(() => expect(watch.polls).toHaveLength(2))
+ expect(getAccessSpy).toHaveBeenLastCalledWith({ sincePairingUseSeq: 4 })
+ expect(screen.getByRole('dialog')).not.toBeNull()
+ expect(screen.getByTestId('remote-share-pairing').textContent).toBe(PAIR_CODE)
+ })
+
+ it('长轮询失败不关闭,常规状态刷新后重新订阅', async () => {
+ vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] })
+ const watch = mockPairingWatch()
+ render(<RemoteShare />)
+ await openShare()
+ await waitFor(() => expect(watch.polls).toHaveLength(1))
+ await act(async () => watch.polls[0]!.reject(new Error('connection lost')))
+ expect(screen.getByRole('dialog')).not.toBeNull()
+ expect(watch.polls).toHaveLength(1)
+
+ await act(async () => vi.advanceTimersByTimeAsync(5000))
+ expect(screen.getByRole('dialog')).not.toBeNull()
+ expect(watch.polls).toHaveLength(2)
+ })
+
+ it.each([undefined, '1', -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1])('旧宿主或非法 marker %s 不启动忙循环', async (usedSeq) => {
+ getAccessSpy.mockResolvedValue(statusOf({ ...listening, pairing: pairingOf({ usedSeq }) }))
+ render(<RemoteShare />)
+ await openShare()
+ await screen.findByTestId('remote-share-pairing')
+ expect(getAccessSpy.mock.calls).toEqual([[undefined]])
+ expect(screen.getByRole('dialog')).not.toBeNull()
+ })
+
+ it('手动关闭后重开,旧订阅迟到的消费响应不关闭新弹层或覆盖新码', async () => {
+ const watch = mockPairingWatch()
+ render(<RemoteShare />)
+ await openShare()
+ await waitFor(() => expect(watch.polls).toHaveLength(1))
+ closeShare()
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ watch.update(consumedStatus(1))
+ await openShare()
+ await waitFor(() => expect(watch.polls).toHaveLength(2))
+
+ await act(async () => watch.polls[0]!.resolve(consumedStatus(1, '999999')))
+
+ expect(screen.getByRole('dialog')).not.toBeNull()
+ expect(screen.getByTestId('remote-share-pairing').textContent).toBe('735026')
+ expect(getAccessSpy).toHaveBeenCalledTimes(4)
+ })
+
+ it('卸载后迟到的消费响应不拉起新请求或影响下一次挂载', async () => {
+ const watch = mockPairingWatch()
+ const view = render(<RemoteShare />)
+ await openShare()
+ await waitFor(() => expect(watch.polls).toHaveLength(1))
+ view.unmount()
+ await act(async () => watch.polls[0]!.resolve(consumedStatus(1)))
+ expect(screen.queryByRole('dialog')).toBeNull()
+ expect(getAccessSpy).toHaveBeenCalledTimes(2)
+
+ render(<RemoteShare />)
+ expect(screen.queryByRole('dialog')).toBeNull()
+ expect(getAccessSpy).toHaveBeenCalledTimes(2)
+ })
+
+ it('长轮询消费响应到达时动作锁仍守住结果,动作完成后立即刷新并关闭', async () => {
+ const watch = mockPairingWatch()
+ const mutation = Promise.withResolvers<unknown>()
+ postAccessTunnelSpy.mockReturnValue(mutation.promise)
+ render(<RemoteShare />)
+ await openShare()
+ await waitFor(() => expect(watch.polls).toHaveLength(1))
+ clickTunnelTab()
+ fireEvent.click(screen.getByText('remote.share.tunnel_enable'))
+ expect(postAccessTunnelSpy).toHaveBeenCalledTimes(1)
+ await act(async () => watch.polls[0]!.resolve(consumedStatus(1)))
+ expect(screen.getByRole('dialog')).not.toBeNull()
+
+ await act(async () => mutation.resolve(statusOf({
+ ...listening,
+ pairing: pairingOf({ usedSeq: 1, code: '735026' }),
+ tunnel: { state: 'running', mode: 'quick' },
+ })))
+
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ watch.update(statusOf({
+ ...listening,
+ pairing: pairingOf({ usedSeq: 1, code: '735026' }),
+ tunnel: { state: 'running', mode: 'quick' },
+ }))
+ await openShare()
+ clickTunnelTab()
+ expect((await screen.findByText('remote.share.tunnel_stop') as HTMLButtonElement).disabled).toBe(false)
+ })
+})
+
+describe('remoteShare 远程分享弹层', () => {
+ it('未打开弹层时不拉取状态', () => {
+ render(<RemoteShare onManage={vi.fn()} />)
+ expect(screen.queryByRole('dialog')).toBeNull()
+ expect(getAccessSpy).not.toHaveBeenCalled()
+ })
+
+ it('弹层由「远程」按钮开合,Esc 可关闭', async () => {
+ render(<RemoteShare onManage={vi.fn()} />)
+ const trigger = screen.getByRole('button', { name: 'remote.share' })
+ expect(screen.queryByTestId('remote-share-panel')).toBeNull()
+
+ fireEvent.click(trigger)
+ expect(await screen.findByTestId('remote-share-panel')).not.toBeNull()
+
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
+ await waitFor(() => expect(screen.queryByTestId('remote-share-panel')).toBeNull())
+ })
+
+ it('dSH Mobile 卡显示用途,整块点击在系统浏览器打开 releases', async () => {
+ render(<RemoteShare />)
+ await openShare()
+ const mobile = screen.getByRole('button', { name: 'remote.share.mobile remote.share.mobile_hint' })
+ expect(mobile.querySelector('svg')).not.toBeNull()
+ expect(screen.queryByText('remote.share.mobile_pending')).toBeNull()
+ expect(screen.queryByText('remote.share.mobile_released')).toBeNull()
+
+ fireEvent.click(screen.getByText('remote.share.mobile_hint'))
+
+ await waitFor(() => expect(openUrlSpy).toHaveBeenCalledExactlyOnceWith({
+ url: 'https://github.com/dsh-tauri/deepseek-harness-desktop/releases',
+ }))
+ })
+
+ it('dSH Mobile 外链打开失败在弹层显示错误', async () => {
+ openUrlSpy.mockRejectedValue(new Error('browser unavailable'))
+ render(<RemoteShare />)
+ await openShare()
+
+ fireEvent.click(screen.getByText('remote.share.mobile'))
+
+ expect(await screen.findByText(/browser unavailable/u)).not.toBeNull()
+ })
+
+ it('局域网未开启:只给开启入口,动作成功后立刻显示新的可达链接', async () => {
+ render(<RemoteShare onManage={vi.fn()} />)
+ await openShare()
+ expect(await screen.findByText('remote.share.lan_enable')).toBeTruthy()
+
+ fireEvent.click(screen.getByText('remote.share.lan_enable'))
+
+ await waitFor(() => expect(postAccessSpy).toHaveBeenCalledWith({ enabled: true }))
+ expect(await screen.findByText(LAN_LINK)).toBeTruthy()
+ })
+
+ it('局域网未开启:有待选地址时带推荐的非回环地址,跳过回环与未推荐项', async () => {
+ getAccessSpy.mockResolvedValue(statusOf({
+ addresses: [
+ { address: '127.0.0.1', recommended: true },
+ { address: '10.0.0.9', recommended: false },
+ { address: '192.168.1.5', recommended: true },
+ ],
+ }))
+ render(<RemoteShare onManage={vi.fn()} />)
+ await openShare()
+
+ fireEvent.click(await screen.findByText('remote.share.lan_enable'))
+
+ await waitFor(() => expect(postAccessSpy).toHaveBeenCalledWith({ enabled: true, address: '192.168.1.5' }))
+ })
+
+ it('局域网已开启:显示链接、二维码与复制按钮', async () => {
+ getAccessSpy.mockResolvedValue(statusOf(listening))
+ render(<RemoteShare onManage={vi.fn()} />)
+ await openShare()
+
+ const link = await screen.findByText(LAN_LINK)
+ expect(link.className).toContain('truncate')
+ expect(link.tagName).toBe('DIV')
+ expect(link.className).not.toContain('break-all')
+ expect(screen.getByRole('img', { name: 'remote.share.qr_alt' }).getAttribute('src')).toBe(QR)
+ expect(screen.queryByText('remote.share.lan_local_only')).toBeNull()
+ expect(screen.queryByText('remote.share.lan_state.listening')).toBeNull()
+
+ fireEvent.click(screen.getByRole('button', { name: 'remote.share.copy' }))
+ await waitFor(() => expect(clipboardSpy).toHaveBeenCalledWith(LAN_LINK, 'remote.share.copied'))
+ })
+
+ it('回环来源:不给链接、二维码与复制,只给仅本机可用的提示', async () => {
+ getAccessSpy.mockResolvedValue(statusOf({
+ ...listening,
+ link: 'http://127.0.0.1:3080/?auth=482913',
+ maskLink: 'http://127.0.0.1:3080/?auth=***',
+ pairing: pairingOf({ link: 'http://127.0.0.1:3080/?auth=482913' }),
+ }))
+ render(<RemoteShare onManage={vi.fn()} />)
+ await openShare()
+
+ expect(await screen.findByText('remote.share.lan_local_only')).toBeTruthy()
+ expect(screen.queryByText(/127\.0\.0\.1/u)).toBeNull()
+ expect(screen.queryByRole('img')).toBeNull()
+ expect(screen.queryByText('remote.share.copy')).toBeNull()
+ })
+
+ it('隧道关闭:只显示启用入口', async () => {
+ render(<RemoteShare onManage={vi.fn()} />)
+ await openShare()
+ clickTunnelTab()
+
+ const offDescription = await screen.findByText('remote.share.tunnel_off_desc')
+ expect(offDescription.className).toContain('text-center')
+ expect(offDescription.className).toContain('block')
+ expect(offDescription.className).toMatch(/pb-/u)
+ expect(await screen.findByText('remote.share.tunnel_enable')).toBeTruthy()
+ expect(screen.queryByText('remote.share.tunnel_failed')).toBeNull()
+ })
+
+ it('隧道启动中:显示阶段与下载进度', async () => {
+ getAccessSpy.mockResolvedValue(statusOf({
+ tunnel: { state: 'starting', mode: 'quick', progress: { stage: 'download', received: 1048576, total: 4194304 } },
+ }))
+ render(<RemoteShare onManage={vi.fn()} />)
+ await openShare()
+ clickTunnelTab()
+
+ expect(await screen.findByText('remote.share.stage.download')).toBeTruthy()
+ expect(screen.getByText('remote.share.download_progress')).toBeTruthy()
+ expect(screen.getByText(/remote\.share\.tunnel_starting/u).textContent).toBe('remote.share.tunnel_starting(remote.share.stage.download)')
+ })
+
+ it('隧道失败:显示原因并可重试', async () => {
+ postAccessTunnelSpy.mockResolvedValue(statusOf({
+ pairing: pairingOf({ tunnelLink: TUNNEL_LINK, tunnelQr: QR }),
+ tunnel: { state: 'running', mode: 'quick', link: TUNNEL_LINK, qr: QR },
+ }))
+ getAccessSpy.mockResolvedValue(statusOf({ tunnel: { state: 'error', mode: 'quick', error: 'dial failed' } }))
+ render(<RemoteShare onManage={vi.fn()} />)
+ await openShare()
+ clickTunnelTab()
+
+ expect(await screen.findByText(/dial failed/)).toBeTruthy()
+ fireEvent.click(screen.getByText('remote.connect.retry'))
+
+ await waitFor(() => expect(postAccessTunnelSpy).toHaveBeenCalledWith({ mode: 'quick' }))
+ expect(await screen.findByText(TUNNEL_LINK)).toBeTruthy()
+ })
+
+ it('隧道就绪:显示隧道链接、二维码与临时配对码', async () => {
+ getAccessSpy.mockResolvedValue(statusOf({
+ pairing: pairingOf({ tunnelLink: TUNNEL_LINK, tunnelQr: QR }),
+ tunnel: { state: 'running', mode: 'quick', link: 'https://demo.trycloudflare.com/?auth=tok', qr: QR },
+ }))
+ render(<RemoteShare onManage={vi.fn()} />)
+ await openShare()
+ clickTunnelTab()
+
+ const link = await screen.findByText(TUNNEL_LINK)
+ expect(link.className).toContain('truncate')
+ expect(link.tagName).toBe('DIV')
+ expect(link.className).not.toContain('break-all')
+ const code = screen.getByTestId('remote-share-pairing')
+ expect(code.textContent).toBe(PAIR_CODE)
+ expect(code.previousElementSibling?.textContent).toBe('remote.share.pairing_expires')
+ expect(screen.getByText('remote.share.pairing_expires')).toBeTruthy()
+ expect(screen.getByText('remote.share.pairing_hint')).toBeTruthy()
+ })
+
+ it('配对码过期:重新拉取状态换新码,且不因同一过期时间反复重试', async () => {
+ getAccessSpy.mockResolvedValue(statusOf({
+ pairing: pairingOf({ expiresAt: Date.now() - 1000 }),
+ tunnel: { state: 'running', mode: 'quick' },
+ }))
+ render(<RemoteShare onManage={vi.fn()} />)
+ await openShare()
+ clickTunnelTab()
+
+ expect(await screen.findByTestId('remote-share-pairing')).toBeTruthy()
+ await waitFor(() => expect(getAccessSpy).toHaveBeenCalledTimes(2))
+ expect(getAccessSpy).toHaveBeenCalledTimes(2)
+ })
+
+ it('只开隧道、不开局域网:局域网栏给仅本机提示,隧道栏仍给短期链接与二维码', async () => {
+ getAccessSpy.mockResolvedValue(statusOf({
+ pairing: { code: PAIR_CODE, expiresAt: Date.now() + 300_000, tunnelLink: TUNNEL_LINK, tunnelQr: QR },
+ tunnel: { state: 'running', mode: 'quick' },
+ }))
+ render(<RemoteShare onManage={vi.fn()} />)
+ await openShare()
+
+ expect(await screen.findByText('remote.share.lan_off_desc')).toBeTruthy()
+ clickTunnelTab()
+
+ await screen.findByText(TUNNEL_LINK)
+ expect(screen.getByText(TUNNEL_LINK)).toBeTruthy()
+ expect(screen.getByRole('img', { name: 'remote.share.qr_alt' }).getAttribute('src')).toBe(QR)
+ expect(screen.getByTestId('remote-share-pairing').textContent).toBe(PAIR_CODE)
+ })
+
+ it('动作返回的访问密码明文只在弹层里保留,可复制可关闭', async () => {
+ postAccessSpy.mockResolvedValue(statusOf({ ...listening, generatedPassword: 'Gen-Pass-1234' }))
+ render(<RemoteShare onManage={vi.fn()} />)
+ await openShare()
+ fireEvent.click(await screen.findByText('remote.share.lan_enable'))
+
+ expect((await screen.findByTestId('remote-share-password')).textContent).toBe('Gen-Pass-1234')
+ fireEvent.click(screen.getByTestId('remote-share-password-copy'))
+ await waitFor(() => expect(clipboardSpy).toHaveBeenCalledWith('Gen-Pass-1234', 'remote.share.copied'))
+
+ fireEvent.click(screen.getByTestId('remote-share-password-dismiss'))
+ expect(screen.queryByTestId('remote-share-password')).toBeNull()
+ })
+
+ it('动作进行中打到轮询:结果不被丢弃,按钮也不会永久锁死', async () => {
+ vi.useFakeTimers()
+ try {
+ let resolveTunnel: ((value: unknown) => void) | undefined
+ postAccessTunnelSpy.mockImplementation(() => new Promise((resolve) => {
+ resolveTunnel = resolve
+ }))
+ getAccessSpy.mockResolvedValue(statusOf({
+ tunnel: { enabled: false, mode: 'quick', state: 'stopped', events: [] },
+ }))
+ render(<RemoteShare onManage={vi.fn()} />)
+ fireEvent.click(screen.getByRole('button', { name: 'remote.share' }))
+ await vi.advanceTimersByTimeAsync(0)
+ fireEvent.click(screen.getByText('remote.share.tab_tunnel'))
+ fireEvent.click(screen.getByText('remote.share.tunnel_enable'))
+ await vi.advanceTimersByTimeAsync(0)
+ expect(postAccessTunnelSpy).toHaveBeenCalledTimes(1)
+
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(getAccessSpy).toHaveBeenCalledTimes(1)
+
+ resolveTunnel?.(statusOf({
+ pairing: pairingOf({ tunnelLink: TUNNEL_LINK, tunnelQr: QR }),
+ tunnel: { state: 'running', mode: 'quick' },
+ }))
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(screen.getByText(TUNNEL_LINK)).toBeTruthy()
+ expect((screen.getByText('remote.share.tunnel_stop') as HTMLButtonElement).disabled).toBe(false)
+ }
+ finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('齿轮保留在标题右侧且打通设置定位链路,缺席时点击不动作', async () => {
+ const manageSpy = vi.fn()
+ const { unmount } = render(<RemoteShare onManage={manageSpy} />)
+ await openShare()
+ const gear = screen.getByRole('button', { name: 'remote.share.settings' })
+ const heading = screen.getByRole('heading', { name: 'remote.share' })
+ expect(gear.parentElement).toBe(heading.parentElement)
+ expect(gear.parentElement?.contains(screen.getByRole('tablist'))).toBe(false)
+ expect(gear.className).toContain('ml-auto')
+ fireEvent.click(gear)
+ expect(manageSpy).toHaveBeenCalledTimes(1)
+ unmount()
+
+ render(<RemoteShare />)
+ await openShare()
+ fireEvent.click(screen.getByRole('button', { name: 'remote.share.settings' }))
+ expect(manageSpy).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/layout/components/remote-share.tsx b/src/layout/components/remote-share.tsx
new file mode 100644
index 00000000..bdef9ce6
--- /dev/null
+++ b/src/layout/components/remote-share.tsx
@@ -0,0 +1,566 @@
+import { ArrowUpRightFromSquare, Copy, Gear, Smartphone, TriangleExclamation } from '@gravity-ui/icons'
+import { Button, Description, Label, Popover, ProgressBar, Spinner, Tabs } from '@heroui/react'
+import { useIntervalFn, useUnmount, useUnmountedRef, useWatch } from '@reause/core'
+import { invoke } from '@tauri-apps/api/core'
+import { useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { If } from 'react-if-lite'
+import { deleteAccessTunnel, getAccess, postAccess, postAccessTunnel } from '@/apis/remote'
+import { writeClipboardText } from '@/utils/clipboard'
+
+interface AccessPairing {
+ code: string
+ expiresAt: number
+ usedSeq?: number
+ link?: string
+ qr?: string
+ tunnelLink?: string
+ tunnelQr?: string
+}
+
+interface AccessTunnel {
+ enabled?: boolean
+ mode?: 'quick' | 'token'
+ hostname?: string | null
+ state?: 'stopped' | 'starting' | 'running' | 'error'
+ url?: string
+ port?: number
+ link?: string
+ qr?: string
+ progress?: { stage?: string, url?: string, received?: number, total?: number }
+ error?: string
+}
+
+interface AccessStatus {
+ version?: number
+ enabled?: boolean
+ state?: 'stopped' | 'listening' | 'error'
+ listening?: boolean
+ listen?: { address?: string, port?: number }
+ port?: number
+ addresses?: { address?: string, recommended?: boolean }[]
+ link?: string
+ maskLink?: string
+ qr?: string
+ linkSource?: 'loopback' | 'lan'
+ error?: string
+ warnings?: string[]
+ pairing?: AccessPairing
+ generatedPassword?: string
+ tunnel?: AccessTunnel
+}
+
+const POLL_INTERVAL = 5000
+
+const LOOPBACK_LINK = /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0|\[::\])(?::|\/|$)/i
+
+const UNUSABLE_ADDRESS = /^(?:127\.0\.0\.1|localhost|0\.0\.0\.0|::1|::)$/i
+
+function isShareableLink(link: string | undefined): link is string {
+ return link !== undefined && link !== '' && !LOOPBACK_LINK.test(link)
+}
+
+function isUnusableAddress(address: string | undefined): boolean {
+ return address === undefined || address === '' || UNUSABLE_ADDRESS.test(address)
+}
+
+function megabytesOf(bytes: number | undefined): string {
+ return bytes === undefined ? '0' : (bytes / 1048576).toFixed(1)
+}
+
+function clockOf(milliseconds: number): string {
+ const seconds = Math.max(0, Math.ceil(milliseconds / 1000))
+ return `${String(Math.floor(seconds / 60)).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`
+}
+
+function pairingUseSeqOf(status: AccessStatus | null): number | undefined {
+ const seq = status?.pairing?.usedSeq
+ return typeof seq === 'number' && Number.isSafeInteger(seq) && seq >= 0 ? seq : undefined
+}
+
+export function RemoteShare({ onManage }: { onManage?: () => void }) {
+ const { t } = useTranslation()
+ const [open, setOpen] = useState(false)
+ const [status, setStatus] = useState<AccessStatus | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [busy, setBusy] = useState(false)
+ const [generatedPassword, setGeneratedPassword] = useState<string | null>(null)
+ const [now, setNow] = useState(() => Date.now())
+ const requestSeqRef = useRef(0)
+ const mutationSeqRef = useRef(0)
+ const busyRef = useRef(false)
+ const refreshedExpiryRef = useRef<number | null>(null)
+ const openRef = useRef(false)
+ const sessionRef = useRef(0)
+ const watchSessionRef = useRef<number | null>(null)
+ const baselineRef = useRef<number | undefined>(undefined)
+ const consumedRef = useRef(false)
+ const unmountedRef = useUnmountedRef()
+
+ function changeOpen(next: boolean) {
+ if (openRef.current === next)
+ return
+ openRef.current = next
+ sessionRef.current += 1
+ requestSeqRef.current += 1
+ baselineRef.current = undefined
+ consumedRef.current = false
+ refreshedExpiryRef.current = null
+ if (next) {
+ setStatus(null)
+ setNow(Date.now())
+ }
+ setOpen(next)
+ }
+
+ function updateStatus(raw: AccessStatus, consumed = false) {
+ setStatus(raw)
+ setError(raw?.error ?? null)
+ const nextSeq = pairingUseSeqOf(raw)
+ if (consumed || (baselineRef.current !== undefined && nextSeq !== undefined && nextSeq !== baselineRef.current))
+ changeOpen(false)
+ }
+
+ async function load(consumed = false) {
+ if (busyRef.current || !openRef.current || unmountedRef.current)
+ return
+ const seq = ++requestSeqRef.current
+ try {
+ const raw = await getAccess() as unknown as AccessStatus
+ if (seq !== requestSeqRef.current || unmountedRef.current)
+ return
+ updateStatus(raw, consumed)
+ }
+ catch (err) {
+ if (seq !== requestSeqRef.current || unmountedRef.current)
+ return
+ setError(String(err))
+ }
+ }
+
+ async function run(action: () => Promise<unknown>) {
+ if (busyRef.current || !openRef.current || unmountedRef.current)
+ return
+ const seq = ++requestSeqRef.current
+ const mutation = ++mutationSeqRef.current
+ busyRef.current = true
+ setBusy(true)
+ setError(null)
+ try {
+ const raw = await action() as AccessStatus
+ if (seq !== requestSeqRef.current || unmountedRef.current)
+ return
+ updateStatus(raw)
+ if (typeof raw?.generatedPassword === 'string' && raw.generatedPassword !== '')
+ setGeneratedPassword(raw.generatedPassword)
+ }
+ catch (err) {
+ if (seq !== requestSeqRef.current || unmountedRef.current)
+ return
+ setError(String(err))
+ }
+ finally {
+ if (mutation === mutationSeqRef.current && !unmountedRef.current) {
+ busyRef.current = false
+ setBusy(false)
+ }
+ }
+ }
+
+ async function watchPairingUse(session: number, baseline: number) {
+ watchSessionRef.current = session
+ try {
+ while (openRef.current && session === sessionRef.current && !unmountedRef.current) {
+ const raw = await getAccess({ sincePairingUseSeq: baseline }) as unknown as AccessStatus
+ if (!openRef.current || session !== sessionRef.current || unmountedRef.current)
+ return
+ const nextSeq = pairingUseSeqOf(raw)
+ if (nextSeq === undefined)
+ return
+ if (nextSeq !== baseline) {
+ if (busyRef.current) {
+ consumedRef.current = true
+ return
+ }
+ updateStatus(raw)
+ return
+ }
+ if (raw?.error !== undefined)
+ return
+ }
+ }
+ catch {
+ return
+ }
+ finally {
+ if (watchSessionRef.current === session)
+ watchSessionRef.current = null
+ }
+ }
+
+ const poll = useIntervalFn(() => void load(), POLL_INTERVAL, { immediate: false })
+ const clock = useIntervalFn(() => setNow(Date.now()), 1000, { immediate: false })
+ useWatch(open, () => {
+ if (open) {
+ poll.resume()
+ clock.resume()
+ void load()
+ }
+ else {
+ poll.pause()
+ clock.pause()
+ }
+ })
+ useWatch(busy, () => {
+ if (!busy && open && status === null)
+ void load()
+ })
+ useUnmount(() => {
+ openRef.current = false
+ sessionRef.current += 1
+ requestSeqRef.current += 1
+ })
+
+ useWatch([open, status, busy], () => {
+ if (!open || busy || status === null)
+ return
+ if (consumedRef.current) {
+ void load(true)
+ return
+ }
+ const baseline = pairingUseSeqOf(status)
+ if (baseline === undefined)
+ return
+ baselineRef.current ??= baseline
+ if (watchSessionRef.current !== sessionRef.current)
+ void watchPairingUse(sessionRef.current, baselineRef.current)
+ })
+
+ const pairing = status?.pairing
+ useWatch([open, pairing, now, busy], () => {
+ if (!open || busy || pairing === undefined || pairing.expiresAt > now)
+ return
+ if (refreshedExpiryRef.current === pairing.expiresAt)
+ return
+ refreshedExpiryRef.current = pairing.expiresAt
+ void load()
+ })
+
+ function copyLink(link: string) {
+ void writeClipboardText(link, t('remote.share.copied')).catch(() => { })
+ }
+
+ const listening = status?.state === 'listening' || status?.listening === true
+ const shareLink = isShareableLink(pairing?.link) ? pairing.link : null
+ const recommendedAddress = status?.addresses?.find(item => item.recommended === true && !isUnusableAddress(item.address))?.address
+ const tunnel = status?.tunnel
+ const tunnelState = tunnel?.state ?? 'stopped'
+ const tunnelLink = isShareableLink(pairing?.tunnelLink) ? pairing.tunnelLink : null
+ const stage = tunnel?.progress?.stage
+ const received = tunnel?.progress?.received
+ const total = tunnel?.progress?.total
+ const pairingCode = (
+ <div className="flex flex-col gap-1.5 rounded-lg border border-line/40 px-2.5 py-2">
+ <span className="text-[11px] text-muted">{t('remote.share.pairing')}</span>
+ {pairing === undefined
+ ? <span className="text-[11px] text-muted">{t('remote.share.pairing_absent')}</span>
+ : (
+ <>
+ <div className="flex items-center gap-2">
+ <Description className="shrink-0 text-[11px] text-muted">
+ {t('remote.share.pairing_expires', { time: clockOf(pairing.expiresAt - now) })}
+ </Description>
+ <span className="ml-auto font-mono text-base tracking-[0.2em] text-ink" data-testid="remote-share-pairing">
+ {pairing.code}
+ </span>
+ </div>
+ <span className="text-[11px] leading-4 text-muted">{t('remote.share.pairing_hint')}</span>
+ </>
+ )}
+ </div>
+ )
+
+ const passwordBlock = generatedPassword === null
+ ? null
+ : (
+ <div className="flex flex-col gap-1.5 rounded-lg border border-warning/40 px-2.5 py-2">
+ <span className="text-[11px] text-muted">{t('remote.share.password')}</span>
+ <div className="flex items-center gap-2">
+ <span className="break-all font-mono text-xs text-ink" data-testid="remote-share-password">{generatedPassword}</span>
+ <Button
+ className="ml-auto size-7 shrink-0"
+ isIconOnly
+ size="sm"
+ variant="ghost"
+ aria-label={t('remote.share.copy')}
+ data-testid="remote-share-password-copy"
+ onPress={() => copyLink(generatedPassword)}
+ >
+ <Copy className="size-3.5" />
+ </Button>
+ <Button
+ className="h-7 shrink-0 text-[11px]"
+ size="sm"
+ variant="ghost"
+ data-testid="remote-share-password-dismiss"
+ onPress={() => setGeneratedPassword(null)}
+ >
+ {t('remote.share.password_dismiss')}
+ </Button>
+ </div>
+ <span className="text-[11px] leading-4 text-muted">{t('remote.share.password_hint')}</span>
+ </div>
+ )
+
+ return (
+ <Popover isOpen={open} onOpenChange={changeOpen}>
+ <Button
+ className="h-7 text-[12.5px] px-1.5 ml-1 gap-1.5"
+ size="sm"
+ variant="ghost"
+ aria-label={t('remote.share')}
+ >
+ <Smartphone />
+ <span>{t('remote.share')}</span>
+ </Button>
+
+ <Popover.Content className="w-88! max-w-[92vw]" data-testid="remote-share-panel">
+ <Popover.Dialog className="space-y-3">
+ <div className="flex items-center gap-2">
+ <Popover.Heading className="text-xs">{t('remote.share')}</Popover.Heading>
+ <Button
+ className="ml-auto size-7 shrink-0"
+ isIconOnly
+ size="sm"
+ variant="ghost"
+ aria-label={t('remote.share.settings')}
+ isDisabled={onManage == null}
+ onPress={onManage}
+ >
+ <Gear className="size-3.5" />
+ </Button>
+ </div>
+
+ <div className="rounded-lg border border-line/40">
+ <Button
+ className="h-auto w-full justify-between py-2 text-left"
+ variant="ghost"
+ onPress={() => void invoke('open_external_url', {
+ url: 'https://github.com/dsh-tauri/deepseek-harness-desktop/releases',
+ }).catch(err => setError(String(err)))}
+ >
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="text-xs text-ink">{t('remote.share.mobile')}</span>
+ <span className="whitespace-normal text-[11px] leading-4 text-muted">{t('remote.share.mobile_hint')}</span>
+ </span>
+ <ArrowUpRightFromSquare className="size-3.5 shrink-0 text-muted" aria-hidden="true" />
+ </Button>
+ </div>
+
+ <If cond={error !== null}>
+ <Description className="break-all text-xs text-danger">
+ {t('remote.share.action_failed')}
+ {' · '}
+ {error}
+ </Description>
+ </If>
+
+ <Tabs defaultSelectedKey="lan" variant="primary">
+ <Tabs.ListContainer>
+ <Tabs.List aria-label={t('remote.share')}>
+ <Tabs.Tab id="lan" className="h-7 px-3 text-xs">
+ {t('remote.share.tab_lan')}
+ <Tabs.Indicator />
+ </Tabs.Tab>
+ <Tabs.Tab id="tunnel" className="h-7 px-3 text-xs">
+ {t('remote.share.tab_tunnel')}
+ <Tabs.Indicator />
+ </Tabs.Tab>
+ </Tabs.List>
+ </Tabs.ListContainer>
+
+ <Tabs.Panel id="lan" className="space-y-3 pt-3">
+ <If cond={status === null}>
+ <Description className="flex items-center gap-1.5 text-xs">
+ <Spinner className="size-3" />
+ {t('remote.share.loading')}
+ </Description>
+ </If>
+
+ <If cond={status !== null && !listening}>
+ <Description className="text-xs">{t('remote.share.lan_off_desc')}</Description>
+ <Button
+ className="h-8 w-full text-xs"
+ variant="primary"
+ size="sm"
+ isDisabled={busy}
+ onPress={() => void run(() => postAccess(
+ recommendedAddress === undefined
+ ? { enabled: true }
+ : { enabled: true, address: recommendedAddress },
+ ))}
+ >
+ {t('remote.share.lan_enable')}
+ </Button>
+ </If>
+
+ <If cond={status !== null && listening}>
+ {shareLink === null && (
+ <div className="flex items-start gap-2 rounded-lg border border-warning/40 px-2.5 py-2">
+ <TriangleExclamation className="mt-0.5 size-3.5 shrink-0 text-warning" />
+ <Description className="text-[11px] leading-4 text-warning">{t('remote.share.lan_local_only')}</Description>
+ </div>
+ )}
+
+ {shareLink !== null && (
+ <>
+ <div className="rounded-md bg-panel2 px-2 py-1.5">
+ <Description className="flex items-center justify-between gap-2 font-mono text-[11px]">
+ <div className="min-w-0 flex-1 truncate py-1">{shareLink}</div>
+ <Button
+ className="size-6 gap-1.5 text-xs shrink-0"
+ variant="ghost"
+ size="sm"
+ isIconOnly
+ aria-label={t('remote.share.copy')}
+ onPress={() => copyLink(shareLink)}
+ >
+ <Copy className="size-3.5" />
+ </Button>
+ </Description>
+ </div>
+ {pairing?.qr !== undefined && (
+ <div className="flex items-center justify-center rounded-lg bg-panel2 p-2">
+ <img src={pairing.qr} alt={t('remote.share.qr_alt')} className="size-36 rounded-md bg-white p-1" />
+ </div>
+ )}
+ </>
+ )}
+ {pairingCode}
+ {passwordBlock}
+ </If>
+ </Tabs.Panel>
+
+ <Tabs.Panel id="tunnel" className="space-y-3 pt-3">
+ <If cond={status === null}>
+ <Description className="flex items-center gap-1.5 text-xs">
+ <Spinner className="size-3" />
+ {t('remote.share.loading')}
+ </Description>
+ </If>
+
+ <If cond={status !== null && tunnelState === 'stopped'}>
+ <Description className="pb-1 text-center text-xs block">{t('remote.share.tunnel_off_desc')}</Description>
+ <Button
+ className="h-8 w-full text-xs"
+ variant="primary"
+ size="sm"
+ isDisabled={busy}
+ onPress={() => void run(() => postAccessTunnel({ mode: 'quick' }))}
+ >
+ {t('remote.share.tunnel_enable')}
+ </Button>
+ </If>
+
+ <If cond={status !== null && tunnelState === 'starting'}>
+ <div className="flex flex-col gap-4 justify-center items-center">
+ <Description className="flex items-center gap-1.5 text-xs">
+ <Spinner className="size-3" />
+ {t('remote.share.tunnel_starting')}
+ <If cond={stage}>
+ (
+ {t(`remote.share.stage.${stage}`)}
+ )
+ </If>
+ </Description>
+ {total !== undefined && (
+ <>
+ <ProgressBar
+ size="sm"
+ value={Math.min(100, ((received ?? 0) / (total || 1)) * 100)}
+ className="w-full"
+ valueLabel={t('remote.share.download_progress', { received: megabytesOf(received), total: megabytesOf(total) })}
+ >
+ <Label>{t('remote.share.stage.download')}</Label>
+ <ProgressBar.Output className="text-xs text-muted tabular-nums" />
+ <ProgressBar.Track>
+ <ProgressBar.Fill className="bg-info" />
+ </ProgressBar.Track>
+ </ProgressBar>
+ </>
+ )}
+ <Button
+ className="h-8 w-full text-xs"
+ variant="tertiary"
+ size="sm"
+ isDisabled={busy}
+ onPress={() => void run(() => deleteAccessTunnel())}
+ >
+ {t('remote.share.tunnel_stop')}
+ </Button>
+ </div>
+ </If>
+
+ <If cond={status !== null && tunnelState === 'error'}>
+ <Description className="break-all text-xs text-danger">
+ {t('remote.share.tunnel_failed')}
+ {tunnel?.error === undefined ? '' : ` · ${tunnel.error}`}
+ </Description>
+ <Button
+ className="h-8 w-full text-xs"
+ variant="primary"
+ size="sm"
+ isDisabled={busy}
+ onPress={() => void run(() => postAccessTunnel({ mode: tunnel?.mode ?? 'quick' }))}
+ >
+ {t('remote.connect.retry')}
+ </Button>
+ </If>
+
+ <If cond={status !== null && tunnelState === 'running'}>
+ {tunnelLink !== null && (
+ <>
+ <div className="rounded-md bg-panel2 px-2 py-1.5">
+ <Description className="flex items-center justify-between gap-2 font-mono text-[11px]">
+ <div className="min-w-0 flex-1 truncate py-1">{tunnelLink}</div>
+ <Button
+ className="size-6 gap-1.5 text-xs shrink-0"
+ variant="ghost"
+ size="sm"
+ isIconOnly
+ aria-label={t('remote.share.copy')}
+ onPress={() => copyLink(tunnelLink)}
+ >
+ <Copy className="size-3.5" />
+ </Button>
+ </Description>
+ </div>
+ </>
+ )}
+
+ {pairing?.tunnelQr !== undefined && (
+ <div className="flex items-center justify-center rounded-lg bg-panel2 p-2">
+ <img src={pairing.tunnelQr} alt={t('remote.share.qr_alt')} className="size-36 rounded-md bg-white p-1" />
+ </div>
+ )}
+
+ {pairingCode}
+ {passwordBlock}
+
+ <Button
+ className="h-8 w-full text-xs"
+ variant="tertiary"
+ size="sm"
+ isDisabled={busy}
+ onPress={() => void run(() => deleteAccessTunnel())}
+ >
+ {t('remote.share.tunnel_stop')}
+ </Button>
+ </If>
+ </Tabs.Panel>
+ </Tabs>
+ </Popover.Dialog>
+ </Popover.Content>
+ </Popover>
+ )
+}
diff --git a/src/layout/components/remote-switcher.test.tsx b/src/layout/components/remote-switcher.test.tsx
index 18fdf438..186a556e 100644
--- a/src/layout/components/remote-switcher.test.tsx
+++ b/src/layout/components/remote-switcher.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import type { ComponentProps } from 'react'
-import type { SshMachineRow } from '@/hooks/use-remote'
+import type { RemoteMachineRow } from '@/hooks/use-remote'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -31,12 +31,12 @@ vi.mock('@tauri-apps/api/core', () => ({
}))
vi.mock('@tauri-apps/api/window', () => ({ getCurrentWindow: () => windowInfo }))
-function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {
+function machineOf(partial: Partial<RemoteMachineRow>): RemoteMachineRow {
return { id: 'm1', name: 'machine', state: 'disconnected', ...partial }
}
let queryClient: QueryClient
-let engineMachines: SshMachineRow[]
+let engineMachines: RemoteMachineRow[]
let engineEnabled: boolean
let engineUnreachable: boolean
let eventItems: { seq: number, line: string }[]
@@ -91,20 +91,20 @@ beforeEach(() => {
if (command !== 'remote')
throw new Error(`Unexpected native command: ${command}`)
switch (args?.method) {
- case 'GET /api/tauri/ssh/machines':
+ case 'GET /api/tauri/remote/machines':
if (engineUnreachable)
throw new TypeError('fetch failed')
return { enabled: engineEnabled, items: engineMachines, discovered: [] }
- case 'GET /api/tauri/ssh/machines/events': {
+ case 'GET /api/tauri/remote/machines/events': {
const { sinceSeq } = args.payload as { sinceSeq: number }
return { items: eventItems.filter(item => item.seq >= sinceSeq) }
}
- case 'POST /api/tauri/ssh/machines/connect': {
+ case 'POST /api/tauri/remote/machines/connect': {
const { machineId } = args.payload as { machineId: string }
engineMachines = engineMachines.map(machine => machine.id === machineId ? { ...machine, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' } : machine)
return { tunnelBaseUrl: 'http://127.0.0.1:4001' }
}
- case 'POST /api/tauri/ssh/machines/disconnect': {
+ case 'POST /api/tauri/remote/machines/disconnect': {
const { machineId } = args.payload as { machineId: string }
engineMachines = engineMachines.map(machine => machine.id === machineId ? { ...machine, state: 'disconnected', tunnelBaseUrl: undefined } : machine)
return {}
@@ -199,7 +199,7 @@ describe('remoteSwitcher 交互与降级', () => {
engineEnabled = false
renderSwitcher()
await waitFor(() => {
- expect(invokeSpy).toHaveBeenCalledWith('remote', { method: 'GET /api/tauri/ssh/machines', payload: null })
+ expect(invokeSpy).toHaveBeenCalledWith('remote', { method: 'GET /api/tauri/remote/machines', payload: null })
expect(queryClient.getQueryState(queryKeys.remoteMachines)?.status).toBe('success')
expect(queryClient.getQueryState(queryKeys.remoteMachines)?.fetchStatus).toBe('idle')
})
@@ -221,7 +221,7 @@ describe('remoteSwitcher 交互与降级', () => {
const menu = await openMenu()
expect(within(menu).getByText('alpha').closest('[role="menuitem"]')?.textContent).toContain('remote.state.connected')
expect(within(menu).getByText('remote.disconnect_active')).toBeTruthy()
- expect(requests('POST /api/tauri/ssh/machines/connect')).toHaveLength(0)
+ expect(requests('POST /api/tauri/remote/machines/connect')).toHaveLength(0)
})
it('点击本地项:回本地并撤销挂起切换', async () => {
@@ -245,7 +245,7 @@ describe('remoteSwitcher 交互与降级', () => {
expect(changeSpy).toHaveBeenLastCalledWith('', null)
expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('remote.local')
expect(screen.queryByRole('dialog')).toBeNull()
- expect(requests('POST /api/tauri/ssh/machines/disconnect')).toHaveLength(0)
+ expect(requests('POST /api/tauri/remote/machines/disconnect')).toHaveLength(0)
const menu = await openMenu()
expect(within(menu).getByText('beta').closest('[role="menuitem"]')?.getAttribute('aria-disabled')).not.toBe('true')
expect(within(menu).queryByText('remote.disconnect_active')).toBeNull()
@@ -263,7 +263,7 @@ describe('remoteSwitcher 交互与降级', () => {
expect(item?.getAttribute('aria-disabled')).toBe('true')
fireEvent.click(within(menu).getByText('alpha'))
expect(changeSpy).toHaveBeenLastCalledWith('', null)
- expect(requests('POST /api/tauri/ssh/machines/connect')).toHaveLength(0)
+ expect(requests('POST /api/tauri/remote/machines/connect')).toHaveLength(0)
engineUnreachable = false
fireEvent(window, new Event('focus'))
@@ -308,7 +308,7 @@ describe('remoteSwitcher 交互与降级', () => {
expect(changeSpy).toHaveBeenLastCalledWith('', null)
fireEvent.click(within(dialog).getByRole('button', { name: 'remote.connect.cancel' }))
await waitFor(() => {
- expect(invokeSpy).toHaveBeenCalledWith('remote', { method: 'POST /api/tauri/ssh/machines/disconnect', payload: { machineId: 'm1' } })
+ expect(invokeSpy).toHaveBeenCalledWith('remote', { method: 'POST /api/tauri/remote/machines/disconnect', payload: { machineId: 'm1' } })
expect(screen.queryByRole('dialog')).toBeNull()
})
expect(changeSpy).toHaveBeenLastCalledWith('', null)
@@ -326,23 +326,23 @@ describe('remoteSwitcher 交互与降级', () => {
expect(screen.queryByRole('button', { name: 'remote.switcher' })).toBeNull()
expect(screen.queryByRole('dialog')).toBeNull()
expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4001', '#123456')
- expect(requests('GET /api/tauri/ssh/machines')).toHaveLength(1)
+ expect(requests('GET /api/tauri/remote/machines')).toHaveLength(1)
engineMachines = [machineOf({ name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4002', color: '#654321', tintBorder: true })]
await act(async () => {
await vi.advanceTimersByTimeAsync(2000)
})
- expect(requests('GET /api/tauri/ssh/machines')).toHaveLength(2)
+ expect(requests('GET /api/tauri/remote/machines')).toHaveLength(2)
expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4002', '#654321')
rerender(switcherElement())
expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('alpha')
expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4002', '#654321')
- expect(requests('POST /api/tauri/ssh/machines/connect')).toHaveLength(0)
+ expect(requests('POST /api/tauri/remote/machines/connect')).toHaveLength(0)
unmount()
await act(async () => {
await vi.advanceTimersByTimeAsync(4000)
})
- expect(requests('GET /api/tauri/ssh/machines')).toHaveLength(2)
+ expect(requests('GET /api/tauri/remote/machines')).toHaveLength(2)
})
})
@@ -358,7 +358,7 @@ describe('remoteSwitcher 增强(4.4)', () => {
fireEvent.click(within(menu).getByText('remote.disconnect_active'))
await waitFor(() => {
- expect(invokeSpy).toHaveBeenCalledWith('remote', { method: 'POST /api/tauri/ssh/machines/disconnect', payload: { machineId: 'm1' } })
+ expect(invokeSpy).toHaveBeenCalledWith('remote', { method: 'POST /api/tauri/remote/machines/disconnect', payload: { machineId: 'm1' } })
expect(changeSpy).toHaveBeenLastCalledWith('', null)
})
expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('remote.local')
@@ -404,7 +404,7 @@ describe('remoteSwitcher 行内双动作(当前窗口 vs 新窗口)', () =>
expect(changeSpy).toHaveBeenLastCalledWith('', null)
expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('remote.local')
expect(screen.queryByRole('dialog')).toBeNull()
- expect(requests('POST /api/tauri/ssh/machines/connect')).toHaveLength(0)
+ expect(requests('POST /api/tauri/remote/machines/connect')).toHaveLength(0)
})
it('未连接机器的新窗口按钮:url 置空(窗口内启动连接流程)', async () => {
@@ -418,7 +418,7 @@ describe('remoteSwitcher 行内双动作(当前窗口 vs 新窗口)', () =>
expect(changeSpy).toHaveBeenLastCalledWith('', null)
expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('remote.local')
expect(screen.queryByRole('dialog')).toBeNull()
- expect(requests('POST /api/tauri/ssh/machines/connect')).toHaveLength(0)
+ expect(requests('POST /api/tauri/remote/machines/connect')).toHaveLength(0)
})
it('机器行显示 user@host:port 副标题', async () => {
diff --git a/src/layout/components/view-menu.test.tsx b/src/layout/components/view-menu.test.tsx
index ce68b296..a3c9124c 100644
--- a/src/layout/components/view-menu.test.tsx
+++ b/src/layout/components/view-menu.test.tsx
@@ -150,6 +150,30 @@ afterAll(() => {
Object.defineProperty(navigator, 'userAgent', { configurable: true, value: userAgent })
})
+describe('shell remote share availability', () => {
+ it.each(['starting', 'preinstall', 'error'])('hides remote sharing while the local service is %s', (status) => {
+ store.harness.status = status
+ render(<Webview />)
+ expect(screen.queryByRole('button', { name: 'remote.share' })).toBeNull()
+ })
+
+ it('hides remote sharing when local health is lost and restores it after recovery', () => {
+ const view = render(<Webview />)
+ expect(screen.getByRole('button', { name: 'remote.share' })).not.toBeNull()
+ store.harness.serviceHealthy = false
+ view.rerender(<Webview />)
+ expect(screen.queryByRole('button', { name: 'remote.share' })).toBeNull()
+ store.harness.serviceHealthy = true
+ view.rerender(<Webview />)
+ expect(screen.getByRole('button', { name: 'remote.share' })).not.toBeNull()
+ })
+
+ it('keeps remote sharing independent of SSH and LAN/tunnel settings while the service bridge is live', () => {
+ render(<Navbar onRemoteChange={vi.fn()} onToggleSidebar={vi.fn()} />)
+ expect(screen.getByRole('button', { name: 'remote.share' })).not.toBeNull()
+ })
+})
+
describe('native View menu state', () => {
it('restores enabled commands and hints after the language change rebuilds the native menu', async () => {
render(<Webview />)
diff --git a/src/layout/components/webview.tsx b/src/layout/components/webview.tsx
index d3ac58b6..0b7c0cee 100644
--- a/src/layout/components/webview.tsx
+++ b/src/layout/components/webview.tsx
@@ -15,6 +15,7 @@ import { useListen } from '@/hooks/use-listen'
import { store } from '@/store'
import { Recovery } from '@/ui/plugin/recovery'
import { Iframe } from './iframe'
+import { REMOTE_SECTION, REMOTE_TAB_ACCESS, REMOTE_TAB_MACHINES } from './nav-bridge'
import { Navbar } from './navbar'
import { Setup } from './setup'
import { PreinstallSetup } from './setup-preinstall'
@@ -28,6 +29,7 @@ interface NavBridgeMessage {
export function Webview() {
const [sidebarCollapsed, setSidebarCollapsed] = useState(false)
const iframeRef = useRef<HTMLIFrameElement>(null)
+ const pendingSettingsTabRef = useRef<string | null>(null)
const appearanceCss = useAppearance(iframeRef)
const post = useIframePost(iframeRef)
@@ -66,6 +68,21 @@ export function Webview() {
setRemoteView({ url, tint })
}
+ function openSettingsTab(tab: string) {
+ post({ type: 'dsh://settings:open', section: REMOTE_SECTION, tab })
+ }
+
+ // 远端视图下 iframe 里是远端页面,设置分区在它那边不存在:先切回本机,
+ // 等本机插件重新 boot 就绪(`dsh://plugin-boot:ready`)再定位,避免发出无人接收的消息。
+ function openLocalSettingsTab(tab: string) {
+ if (remoteMode) {
+ pendingSettingsTabRef.current = tab
+ handleRemoteChange('', null)
+ return
+ }
+ openSettingsTab(tab)
+ }
+
useIframeMessage<NavBridgeMessage>(iframeRef, (data) => {
if (data.type === 'dsh://sidebar:collapsed') {
setSidebarCollapsed(Boolean(data.collapsed))
@@ -73,6 +90,13 @@ export function Webview() {
else if (data.type === 'dsh://shortcuts') {
setDshShortcuts({ rows: parseShortcutRows(data.rows) })
}
+ else if (data.type === 'dsh://plugin-boot:ready') {
+ const pending = pendingSettingsTabRef.current
+ if (pending !== null) {
+ pendingSettingsTabRef.current = null
+ openSettingsTab(pending)
+ }
+ }
})
const renderContent = () => {
@@ -105,6 +129,8 @@ export function Webview() {
onOpenFolder: () => post({ type: 'dsh://workspace:add' }),
onOpenShortcuts: () => post({ type: 'dsh://shortcuts:open' }),
onViewCommand: (command: DshViewCommand) => post({ type: 'dsh://view:command', command }),
+ onOpenMachineManager: () => openLocalSettingsTab(REMOTE_TAB_MACHINES),
+ onOpenRemoteAccess: () => openLocalSettingsTab(REMOTE_TAB_ACCESS),
}
: {}
diff --git a/src/ui/dialog/profile-migrate.test.tsx b/src/ui/dialog/profile-migrate.test.tsx
index b3677fb4..66ac68f0 100644
--- a/src/ui/dialog/profile-migrate.test.tsx
+++ b/src/ui/dialog/profile-migrate.test.tsx
@@ -1,4 +1,5 @@
// @vitest-environment jsdom
+import type { PropsWithOverlays } from '@overlastic/react'
import { OverlaysProvider, useOverlay } from '@overlastic/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { mockIPC } from '@tauri-apps/api/mocks'
@@ -52,8 +53,12 @@ let analysis: ReturnType<typeof fixtures>
let client: QueryClient
let calls: Record<string, unknown[]>
+function TrackedDialog(props: PropsWithOverlays) {
+ return <div data-testid="migration-overlay"><ProfileMigrateDialog {...props} /></div>
+}
+
function Launcher() {
- const open = useOverlay(ProfileMigrateDialog)
+ const open = useOverlay(TrackedDialog)
function handleOpen() {
void open().catch(() => {})
}
@@ -79,6 +84,7 @@ async function openDialog() {
async function submit() {
fireEvent.click(screen.getByText('profiles.migrate_confirm'))
await waitFor(() => expect(calls.migrate).toBeDefined())
+ await waitFor(() => expect(screen.queryByTestId('migration-overlay')).toBeNull())
}
beforeEach(() => {
diff --git a/test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts b/test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts
index a854bb80..737566dd 100644
--- a/test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts
+++ b/test/e2e/plugins/dsh-tauri-mobile-settings.e2e.ts
@@ -153,6 +153,8 @@ describe('mobile settings official host composition', () => {
try {
await current.click()
await expect.poll(() => dialog.getAttribute('data-dsh-mobile-settings-view')).toBe('detail')
+ // 分类列表会随产品可见分区增减而回流:等详情真的落到「通用设置」再操作语言项
+ await expect.poll(() => dialog.locator('[data-dsh-mobile-settings-section-title]').textContent(), { message: '详情必须落到通用设置' }).toBe('通用设置')
await language.getByRole('button', { name: '中文', exact: true }).click()
await menu.getByRole('menuitem', { name: 'English', exact: true }).click()
await expect.poll(() => dialog.getByRole('button', { name: 'Back to settings categories', exact: true }).count(), { message: '真实 locale 变更必须更新附加返回按钮' }).toBe(1)
diff --git a/test/e2e/plugins/dsh-tauri-remote-access.e2e.ts b/test/e2e/plugins/dsh-tauri-remote-access.e2e.ts
new file mode 100644
index 00000000..39919c01
--- /dev/null
+++ b/test/e2e/plugins/dsh-tauri-remote-access.e2e.ts
@@ -0,0 +1,165 @@
+/**
+ * 批次 · `dsh-tauri-remote` 入站暴露(S4/S5)在真实 `dsh web` 宿主里的路由契约。
+ *
+ * 复用 globalSetup 的共享宿主(`DSH_E2E_PLUGIN=dsh-tauri-remote`),因此断言的是**打包产物**:
+ * 插件从 `src-tauri/resources` 加载,`/access` 的二维码生成必须证明 qrcode 已被构建期内联。
+ *
+ * 三条边界都在外部世界:HTTP 状态码、真实监听端口上的转发响应、`<DSH_HOME>/remote/access.json`
+ * 的落盘形态。每个改状态的用例都在 `finally` 里关掉暴露并清空凭据,绝不把端口与凭据留给后续用例。
+ *
+ * 隧道只覆盖**参数校验**:quick 模式会真的去下载 cloudflared(网络依赖),进程生命周期由
+ * `service/tunnel.test.ts` 用注入的桩进程覆盖,不在共享宿主里起真进程。
+ */
+
+import type { Server } from 'node:http'
+import { existsSync, readFileSync } from 'node:fs'
+import { createServer } from 'node:http'
+import { join } from 'node:path'
+import { afterEach, describe, expect, inject, it } from 'vitest'
+
+const BASE = '/api/tauri/remote'
+const ACCESS = `${BASE}/access`
+const TOKEN = `${ACCESS}/token`
+const TUNNEL = `${ACCESS}/tunnel`
+
+interface AccessStatus {
+ enabled: boolean
+ state: string
+ listening: boolean
+ listen: { address: string, port: number }
+ port: number
+ auth: { enabled: boolean, scope: string, hasPassword?: boolean, hasToken?: boolean }
+ link?: string
+ maskLink?: string
+ qr?: string
+ linkSource?: string
+ generatedPassword?: string
+ tunnel: { enabled: boolean, mode: string, state: string, url?: string, qr?: string, progress?: { stage: string, received?: number, total?: number } }
+ localPort?: number
+ error?: string
+ events: Array<{ seq: number, line: string }>
+}
+
+function url(path: string): string {
+ return `${inject('dshBaseUrl')}${path}`
+}
+
+function apiHeaders(extra: Record<string, string> = {}): Record<string, string> {
+ return { 'cookie': inject('dshCookie'), 'content-type': 'application/json', ...extra }
+}
+
+async function readAccess(): Promise<AccessStatus> {
+ const response = await fetch(url(ACCESS), { headers: apiHeaders() })
+ expect(response.status, 'GET /access 必须存在且返回 200').toBe(200)
+ return await response.json() as AccessStatus
+}
+
+async function writeAccess(body: Record<string, unknown>, method = 'POST'): Promise<{ status: number, body: AccessStatus }> {
+ const response = await fetch(url(ACCESS), { method, headers: apiHeaders(), body: JSON.stringify(body) })
+ return { status: response.status, body: await response.json() as AccessStatus }
+}
+
+function freePort(): Promise<number> {
+ const server: Server = createServer()
+ return new Promise((resolve) => {
+ server.listen(0, '127.0.0.1', () => {
+ const address = server.address() as { port: number }
+ server.close(() => resolve(address.port))
+ })
+ })
+}
+
+async function disable(): Promise<AccessStatus> {
+ const response = await writeAccess({ enabled: false })
+ return response.body
+}
+
+/** 每个用例收尾:关暴露、关认证、清密码并把监听地址复位,乱序执行时不把状态留给下一个用例。 */
+afterEach(async () => {
+ await writeAccess({ enabled: false, authEnabled: false, password: null, address: '127.0.0.1' })
+})
+
+describe('入站暴露路由(真实 dsh 宿主)', () => {
+ it('默认态:未监听、无凭据、隧道停止,且不返回链接', async () => {
+ await disable()
+ const status = await readAccess()
+ expect(status.listening).toBe(false)
+ expect(status.state).toBe('stopped')
+ expect(status.link).toBeUndefined()
+ expect(status.qr).toBeUndefined()
+ expect(status.tunnel.state).toBe('stopped')
+ expect(status.tunnel.mode).toBe('quick')
+ expect(status.auth.hasToken).toBe(false)
+ expect(status.auth.hasPassword).toBe(false)
+ })
+
+ it('开启回环监听:真实端口可转发,localPort 取自宿主 webserver 的实监听端口', async () => {
+ const port = await freePort()
+ const started = await writeAccess({ enabled: true, address: '127.0.0.1', port })
+ expect(started.status).toBe(200)
+ expect(started.body.listening).toBe(true)
+ expect(started.body.port).toBe(port)
+ expect(started.body.localPort, '非桌面载体没有 DSH_WEB_PORT,端口必须来自宿主 webserver').toBeGreaterThan(0)
+ expect(started.body.link).toBe(`http://127.0.0.1:${port}/`)
+ expect(started.body.linkSource).toBe('loopback')
+ expect(started.body.qr, '面板需要本地核对用二维码,回环监听也生成').toMatch(/^data:image\/png;base64,/u)
+ expect(started.body.auth.enabled, '开启暴露即自动带认证').toBe(true)
+ expect(started.body.auth.hasPassword, '没有凭据时自动生成密码').toBe(true)
+
+ const proxied = await fetch(`http://127.0.0.1:${port}/`)
+ expect(proxied.status).toBe(200)
+ expect(await proxied.text()).toContain('<')
+
+ const stopped = await disable()
+ expect(stopped.listening).toBe(false)
+ expect(stopped.link).toBeUndefined()
+ }, 60_000)
+
+ it('链接 Token 可签发与作废,链接与二维码只在有 Token 时带 auth 参数', async () => {
+ const port = await freePort()
+ await writeAccess({ enabled: true, address: '0.0.0.0', port, authEnabled: true, password: 'e2e-access-pass', scope: 'public_only' })
+ try {
+ const issued = await fetch(url(TOKEN), { method: 'POST', headers: apiHeaders() })
+ expect(issued.status).toBe(200)
+ const withToken = await issued.json() as AccessStatus
+ expect(withToken.auth.hasToken).toBe(true)
+ expect(withToken.auth.hasPassword).toBe(true)
+ expect(withToken.link).toMatch(/\?auth=/u)
+ expect(withToken.qr, '非回环监听给出二维码,证明打包产物里的二维码编码可用').toMatch(/^data:image\/png;base64,/u)
+ expect(withToken.maskLink).toContain('?auth=***')
+
+ const revoked = await fetch(url(TOKEN), { method: 'DELETE', headers: apiHeaders() })
+ expect(revoked.status).toBe(200)
+ const withoutToken = await revoked.json() as AccessStatus
+ expect(withoutToken.auth.hasToken).toBe(false)
+ expect(withoutToken.link).not.toContain('?auth=')
+ }
+ finally {
+ await disable()
+ }
+ }, 60_000)
+
+ it('隧道参数校验:具名模式缺凭据或主机名时 400,且不落盘', async () => {
+ const missingCredential = await fetch(url(TUNNEL), { method: 'POST', headers: apiHeaders(), body: JSON.stringify({ mode: 'token' }) })
+ expect(missingCredential.status).toBe(400)
+ expect(JSON.stringify(await missingCredential.json())).toContain('Tunnel Token')
+
+ const missingHostname = await fetch(url(TUNNEL), { method: 'POST', headers: apiHeaders(), body: JSON.stringify({ mode: 'token', token: 'cf-token' }) })
+ expect(missingHostname.status).toBe(400)
+ expect(JSON.stringify(await missingHostname.json())).toContain('公开主机名')
+
+ const documentPath = join(inject('dshHome'), 'remote', 'access.json')
+ const document = JSON.parse(existsSync(documentPath) ? readFileSync(documentPath, 'utf8') : '{}') as { tunnel?: { enabled?: boolean } }
+ expect(document.tunnel?.enabled ?? false).toBe(false)
+ expect((await readAccess()).tunnel.state).toBe('stopped')
+ }, 60_000)
+
+ it('管理接口拒绝非回环来源(网关标识声明为公网)', async () => {
+ const response = await fetch(url(ACCESS), {
+ method: 'POST',
+ headers: apiHeaders({ 'x-dsh-remote-source': 'public' }),
+ body: JSON.stringify({ enabled: true }),
+ })
+ expect(response.status).toBe(403)
+ }, 60_000)
+})
diff --git a/test/e2e/plugins/dsh-tauri-remote-panel.e2e.ts b/test/e2e/plugins/dsh-tauri-remote-panel.e2e.ts
new file mode 100644
index 00000000..a694b7f6
--- /dev/null
+++ b/test/e2e/plugins/dsh-tauri-remote-panel.e2e.ts
@@ -0,0 +1,276 @@
+/**
+ * 批次 · `dsh-tauri-remote` 入站访问面板(S6)在真实浏览器里的走查。
+ *
+ * 断言的是**用户可见行为**:设置侧栏「远程访问」页三张分组卡(局域网 / 公网隧道 / 访问控制)的
+ * 渲染与操作回执。面板只保留可配置项与凭据本身——不再渲染链接、二维码、日志、认证开关与监听摘要,
+ * 因此链接形态(回环 / 局域网)、隧道公网地址等数据改为经宿主 `/api/tauri/remote/access` 取回断言,
+ * 面板侧只断言「不出现」以及证书行的显隐往返。截图落在 `test/e2e/.artifacts/`,作为人工复核证据。
+ *
+ * 非回环监听的前置状态用同一套 HTTP 路由布置(面板下拉在 iframe 里的指针命中不稳,
+ * 不适合做断言支点);面板侧只断言渲染与凭据开关的真实回写。
+ * 隧道用例默认关闭:它会真的下载 cloudflared 并占用公网随机域名,不适合放进常规门禁;
+ * 打开后用例自带收尾(停止隧道、关闭暴露),不把状态留给后续用例。
+ */
+
+import type { Browser } from 'playwright'
+import type { DshPage } from '../support/browser'
+import { mkdirSync } from 'node:fs'
+import { join } from 'node:path'
+import process from 'node:process'
+import { afterAll, beforeAll, describe, expect, inject, it } from 'vitest'
+import { launchDshBrowser, newDshPage, openSettings, selectSettingsSection } from '../support/browser'
+
+const ARTIFACTS = join(import.meta.dirname, '..', '.artifacts')
+const ACCESS_API = '/api/tauri/remote/access'
+const PANEL = '[data-testid="access-section"]'
+const LAN = '局域网'
+const TUNNEL = '公网隧道'
+const ACCESS_TOGGLE = '[data-testid="access-toggle"]'
+const LAN_ADDRESS = '[data-testid="access-lan-address"]'
+const LAN_DRAFT = '[data-testid="access-lan-draft"]'
+const PAIRING = '[data-testid="access-pairing"]'
+const PAIRING_CODE = '[data-testid="access-pairing-code"]'
+const PAIRING_COUNTDOWN = '[data-testid="access-pairing-countdown"]'
+const PERMANENT = '[data-testid="access-permanent"]'
+const PERMANENT_VALUE = '[data-testid="access-permanent-value"]'
+const PERMANENT_REVEAL = '[data-testid="access-permanent-reveal"]'
+const TOKEN_ROTATE = '[data-testid="access-token-rotate"]'
+const TOKEN_REVOKE = '[data-testid="access-token-revoke"]'
+const TUNNEL_TOGGLE = '[data-testid="access-tunnel-toggle"]'
+const TUNNEL_MODE = '[data-testid="access-tunnel-mode"]'
+const TUNNEL_START = '[data-testid="access-tunnel-start"]'
+const TUNNEL_STOP = '[data-testid="access-tunnel-stop"]'
+const TUNNEL_STATE = '[data-testid="access-tunnel-state"]'
+const PROGRESS = '[data-testid="access-tunnel-progress"]'
+const REMOVED = [
+ '[data-testid^="access-logs"]',
+ '[data-testid="access-events"]',
+ '[data-testid="access-tunnel-events"]',
+ '[data-testid="access-auth-toggle"]',
+ '[data-testid="access-auth-scope"]',
+ '[data-testid^="access-generated-password"]',
+ '[data-testid="access-link"]',
+ '[data-testid="access-mask-link"]',
+ '[data-testid="access-link-hint"]',
+ '[data-testid="access-pairing-qr"]',
+ '[data-testid="access-permanent-state"]',
+ '[data-testid="access-tunnel-url"]',
+ '[data-testid="access-tunnel-ready"]',
+ '[data-testid="access-tunnel-code"]',
+ '[data-testid="access-tunnel-qr"]',
+].join(', ')
+const CODE = /^[2-9A-HJ-NP-Z]{8}$/u
+const MASK = '••••••••'
+const TUNNEL_E2E = process.env.DSH_E2E_TUNNEL === '1'
+
+interface AccessStatusPayload {
+ enabled: boolean
+ listen: { address: string, port: number }
+ link?: string
+ maskLink?: string
+ linkSource?: string
+ auth: { enabled: boolean, token?: string }
+ pairing?: { code: string, expiresAt: number, link?: string, tunnelLink?: string }
+ tunnel: { enabled: boolean, mode: string, state: string, url?: string }
+}
+
+let browser: Browser
+
+beforeAll(async () => {
+ browser = await launchDshBrowser()
+ mkdirSync(ARTIFACTS, { recursive: true })
+})
+
+afterAll(async () => {
+ await browser?.close()
+})
+
+function apiHeaders(): Record<string, string> {
+ return { 'cookie': inject('dshCookie'), 'content-type': 'application/json' }
+}
+
+async function apiPost(path: string, body: Record<string, unknown>): Promise<void> {
+ const response = await fetch(`${inject('dshBaseUrl')}${path}`, { method: 'POST', headers: apiHeaders(), body: JSON.stringify(body) })
+ expect(response.status, `${path} 必须返回 200`).toBe(200)
+}
+
+async function apiDelete(path: string): Promise<void> {
+ const response = await fetch(`${inject('dshBaseUrl')}${path}`, { method: 'DELETE', headers: apiHeaders() })
+ expect(response.status, `${path} 必须返回 200`).toBe(200)
+}
+
+/** 面板不再展示链接与隧道地址,这些数据的唯一断言支点是宿主状态接口。 */
+async function accessStatus(): Promise<AccessStatusPayload> {
+ const response = await fetch(`${inject('dshBaseUrl')}${ACCESS_API}`, { headers: apiHeaders() })
+ expect(response.status, `${ACCESS_API} 必须返回 200`).toBe(200)
+ return await response.json() as AccessStatusPayload
+}
+
+function authParamOf(link: string | undefined): string | undefined {
+ if (link === undefined)
+ return undefined
+ return new URL(link).searchParams.get('auth') ?? undefined
+}
+
+async function shoot(app: DshPage, name: string): Promise<void> {
+ await app.page.screenshot({ path: join(ARTIFACTS, `${name}.png`) })
+}
+
+function switchOf(app: DshPage, name: string) {
+ return app.frame.getByRole('switch', { name }).first()
+}
+
+async function openAccessPanel(app: DshPage): Promise<void> {
+ await openSettings(app.page, app.frame, app.syntheticFallbacks)
+ await selectSettingsSection(app.page, app.frame, '远程访问', app.syntheticFallbacks)
+ // iframe 内的指针命中偶发丢失(与监听地址下拉同一现象),因此按 aria-selected 重试点击。
+ const tab = app.frame.getByTestId('remote-tabs').getByRole('tab', { name: '远程访问' })
+ await tab.waitFor({ state: 'visible', timeout: 30_000 })
+ await expect.poll(async () => {
+ if (await tab.getAttribute('aria-selected') === 'true')
+ return 'true'
+ await tab.click({ timeout: 5_000 }).catch(() => undefined)
+ return await tab.getAttribute('aria-selected')
+ }, { timeout: 60_000 }).toBe('true')
+ await app.frame.locator(PANEL).waitFor({ state: 'attached', timeout: 20_000 })
+}
+
+async function readText(app: DshPage, selector: string): Promise<string> {
+ return await app.frame.locator(selector).first().textContent() ?? ''
+}
+
+/** 面板已删除的行/块:一律按「不出现」断言,绝不再拿它们做支点。 */
+async function removedCount(app: DshPage): Promise<number> {
+ return await app.frame.locator(PANEL).first().evaluate((panel, selector) => panel.querySelectorAll(selector).length, REMOVED)
+}
+
+/** 用例前后:关暴露、关认证、清密码、复位监听地址并撤销隧道与永久码,不依赖 UI,避免把状态留给同宿主里的后续用例。 */
+async function resetExposure(): Promise<void> {
+ await apiPost(ACCESS_API, { enabled: false, address: '127.0.0.1', authEnabled: false, password: null })
+ await apiDelete(`${ACCESS_API}/tunnel`)
+ await apiDelete(`${ACCESS_API}/token`)
+}
+
+describe('入站访问面板(真实浏览器)', () => {
+ it('只渲染可配置项与凭据:无链接/二维码/日志/认证开关,配对码与宿主链接一致', async () => {
+ await resetExposure()
+ const app = await newDshPage(browser, { ready: '[data-slot="sidebar"]' })
+ try {
+ await openAccessPanel(app)
+ await expect.poll(() => app.frame.locator(PANEL).isVisible()).toBe(true)
+ expect(await app.frame.locator(`${PANEL} img`).count(), '面板不再渲染二维码图片').toBe(0)
+ expect(await removedCount(app), '已删除的行与块不再出现在面板里').toBe(0)
+ expect(await app.frame.locator(LAN_DRAFT).count(), '监听地址未改动时不出现草稿行').toBe(0)
+ expect(await app.frame.locator(PAIRING).count(), '访问控制卡始终给出临时配对码行').toBe(1)
+ expect(await app.frame.locator(PERMANENT).count(), '访问控制卡始终给出永久访问码行').toBe(1)
+ expect(await app.frame.locator(TOKEN_ROTATE).count(), '没有永久码时只给「生成」').toBe(1)
+ expect(await app.frame.locator(PERMANENT_VALUE).count()).toBe(0)
+
+ expect(await app.frame.locator(ACCESS_TOGGLE).count(), '局域网开关暴露 access-toggle').toBe(1)
+ const lan = switchOf(app, LAN)
+ expect(await lan.getAttribute('aria-checked')).toBe('false')
+ await shoot(app, 'access-1-panel')
+
+ await lan.click()
+ await expect.poll(() => lan.getAttribute('aria-checked'), { timeout: 20_000 }).toBe('true')
+ await expect.poll(() => app.frame.locator(LAN_ADDRESS).count(), { timeout: 20_000 }).toBe(1)
+
+ const code = await readText(app, PAIRING_CODE)
+ expect(code, '临时配对码是 8 位无易混淆字符').toMatch(CODE)
+ await expect.poll(() => readText(app, PAIRING_COUNTDOWN), { timeout: 20_000 }).toMatch(/^剩余 \d+:\d{2}$/u)
+ const status = await accessStatus()
+ expect(status.enabled).toBe(true)
+ expect(status.auth.enabled, '开启监听即自动带认证(开关已从面板移出)').toBe(true)
+ expect(status.listen.address).toBe('127.0.0.1')
+ expect(status.linkSource, '回环监听不外发局域网链接').toBe('loopback')
+ expect(status.maskLink, '回环地址只以本机主机名给出').toMatch(/^http:\/\/127\.0\.0\.1:\d+\/$/u)
+ expect(authParamOf(status.link), '回环 + 无永久码时链接不带凭据').toBeUndefined()
+ expect(authParamOf(status.pairing?.link), '面板配对码就是宿主链接里的 auth').toBe(code)
+ await shoot(app, 'access-2-loopback')
+
+ await lan.click()
+ await expect.poll(() => app.frame.locator(LAN_ADDRESS).count(), { timeout: 20_000 }).toBe(0)
+ await expect.poll(() => readText(app, PAIRING_CODE), { timeout: 20_000 }).toBe('开启监听后这里会给出配对码。')
+ expect(await app.frame.locator(PAIRING_COUNTDOWN).count(), '没有配对码时不再渲染倒计时').toBe(0)
+ }
+ finally {
+ await resetExposure()
+ await app.page.close()
+ }
+ }, 120_000)
+
+ it('开放到全部网卡并签发永久码后,永久码掩码/显示/作废可往返', async () => {
+ await resetExposure()
+ await apiPost(ACCESS_API, { enabled: true, address: '0.0.0.0', authEnabled: true, password: 'e2e-panel-pass', scope: 'public_only' })
+ await apiPost(`${ACCESS_API}/token`, {})
+ const app = await newDshPage(browser, { ready: '[data-slot="sidebar"]' })
+ try {
+ await openAccessPanel(app)
+ await expect.poll(() => app.frame.locator(PAIRING_CODE).count(), { timeout: 30_000 }).toBe(1)
+ const status = await accessStatus()
+ expect(status.linkSource, '全部网卡走局域网公开地址').toBe('lan')
+ expect(status.listen.address).toBe('0.0.0.0')
+ expect(status.link, '局域网入口带已签发的永久码').toMatch(/\?auth=/u)
+ expect(status.auth.token).toMatch(CODE)
+ expect(authParamOf(status.pairing?.link), '面板配对码就是宿主链接里的 auth').toBe(await readText(app, PAIRING_CODE))
+ expect(await app.frame.locator(LAN_ADDRESS).count(), '已开启监听时给出监听地址行').toBe(1)
+
+ expect(await app.frame.locator(TOKEN_ROTATE).count(), '已有永久码时不再给「生成」').toBe(0)
+ expect(await readText(app, PERMANENT_VALUE), '永久码默认掩码').toBe(MASK)
+ expect(await app.frame.locator(TOKEN_REVOKE).count()).toBe(1)
+ await shoot(app, 'access-3-permanent-masked')
+
+ await app.frame.locator(PERMANENT_REVEAL).click()
+ await expect.poll(() => readText(app, PERMANENT_VALUE), { timeout: 20_000 }).toMatch(CODE)
+ expect(await readText(app, PERMANENT_VALUE), '点显示才出明文,且与宿主一致').toBe(status.auth.token)
+
+ await app.frame.locator(PERMANENT_REVEAL).click()
+ await expect.poll(() => readText(app, PERMANENT_VALUE), { timeout: 20_000 }).toBe(MASK)
+
+ // 面板必须能把自己签发的永久码作废,否则共享宿主会把凭据留给后续用例
+ await app.frame.locator(TOKEN_REVOKE).click()
+ await expect.poll(() => app.frame.locator(PERMANENT_VALUE).count(), { timeout: 20_000 }).toBe(0)
+ await expect.poll(() => app.frame.locator(TOKEN_ROTATE).count(), { timeout: 20_000 }).toBe(1)
+ expect(authParamOf((await accessStatus()).pairing?.link), '作废永久码不影响临时配对码').toBe(await readText(app, PAIRING_CODE))
+ }
+ finally {
+ await resetExposure()
+ await app.page.close()
+ }
+ }, 120_000)
+
+ it.skipIf(!TUNNEL_E2E)('启动真实 quick 隧道并拿到公网地址,随后停止回收', async () => {
+ await resetExposure()
+ const app = await newDshPage(browser, { ready: '[data-slot="sidebar"]' })
+ try {
+ await openAccessPanel(app)
+ await expect.poll(() => app.frame.locator(TUNNEL_TOGGLE).count(), { timeout: 20_000 }).toBe(1)
+ await switchOf(app, TUNNEL).click()
+ await expect.poll(() => app.frame.locator(TUNNEL_MODE).count(), { timeout: 20_000 }).toBe(1)
+ await app.frame.locator(TUNNEL_START).click()
+ // 启动期边轮询边采样:进度必须在拿到公网地址之前至少出现过一次(不能静默)
+ let sawProgress = false
+ await expect.poll(async () => {
+ if (await app.frame.locator(PROGRESS).count() > 0)
+ sawProgress = true
+ return (await accessStatus()).tunnel.url === undefined ? 0 : 1
+ }, { timeout: 180_000, interval: 500 }).toBe(1)
+ expect(sawProgress, '启动期必须能看到阶段进度').toBe(true)
+
+ const status = await accessStatus()
+ expect(status.tunnel.state).toBe('running')
+ expect(status.tunnel.url, '面板不再展示公网地址,只能从宿主状态取').toMatch(/^https:\/\/[a-z0-9-]+\.trycloudflare\.com$/u)
+ expect(await readText(app, PAIRING_CODE), '隧道链接只带宿主签发的短期配对码').toBe(authParamOf(status.pairing?.tunnelLink))
+ await expect.poll(() => readText(app, TUNNEL_STATE), { timeout: 30_000 }).toBe('隧道运行中')
+ await shoot(app, 'access-4-tunnel')
+
+ await app.frame.locator(TUNNEL_STOP).click()
+ await expect.poll(async () => (await accessStatus()).tunnel.url === undefined, { timeout: 30_000 }).toBe(true)
+ await expect.poll(() => app.frame.locator(TUNNEL_STATE).count(), { timeout: 30_000 }).toBe(0)
+ }
+ finally {
+ await resetExposure()
+ await app.page.close()
+ }
+ }, 300_000)
+})
diff --git a/test/e2e/plugins/dsh-tauri-ssh.e2e.ts b/test/e2e/plugins/dsh-tauri-remote.e2e.ts
similarity index 57%
rename from test/e2e/plugins/dsh-tauri-ssh.e2e.ts
rename to test/e2e/plugins/dsh-tauri-remote.e2e.ts
index f92ea9c0..dca006c4 100644
--- a/test/e2e/plugins/dsh-tauri-ssh.e2e.ts
+++ b/test/e2e/plugins/dsh-tauri-remote.e2e.ts
@@ -1,5 +1,5 @@
/**
- * dsh-tauri-ssh 远程机插件 E2E:真实 ssh2 传输层与真实 SSH 协议往返。
+ * dsh-tauri-remote 远程机插件 E2E:真实 ssh2 传输层与真实 SSH 协议往返。
*
* 四条契约各占一个 describe,共用同一套 `bootHarness` 脚手架——装配真实的
* 运行时单例(`transport` 服务 + `config/runtime.ts` 的 use* 装配面),宿主
@@ -21,23 +21,27 @@
* - reconnect:需要可达的 `ssh dev` 别名机器。
*/
+import type { IncomingMessage } from 'node:http'
+import type { Duplex } from 'node:stream'
import type { Connection, Server as SshServer } from 'ssh2'
-import type { MachineProfile, SshSession } from '../../../packages/dsh-tauri-ssh/src/host/types/index'
+import type { MachineProfile, RemoteHostContext, RemoteSession } from '../../../packages/dsh-tauri-remote/src/host/types/index'
+import { Buffer } from 'node:buffer'
import { execSync } from 'node:child_process'
-import { generateKeyPairSync } from 'node:crypto'
+import { createHash, generateKeyPairSync } from 'node:crypto'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { createServer as createHttpServer } from 'node:http'
import { createServer, connect as tcpConnect } from 'node:net'
import { homedir, tmpdir } from 'node:os'
import process from 'node:process'
import { join } from 'pathe'
import { Server } from 'ssh2'
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'
-import { machineProfiles, resetRuntime, setHostConfig, setMachineDeps } from '../../../packages/dsh-tauri-ssh/src/host/config/runtime'
-import { events } from '../../../packages/dsh-tauri-ssh/src/host/service/events'
-import { machine } from '../../../packages/dsh-tauri-ssh/src/host/service/machine'
-import { transport } from '../../../packages/dsh-tauri-ssh/src/host/service/transport'
-import { MachineId } from '../../../packages/dsh-tauri-ssh/src/host/types/index'
-import { EMPTY_ALLOWLIST } from '../../../packages/dsh-tauri-ssh/src/host/utils/allowlist'
+import { clearHostRuntime, machineProfiles, setCurrentHostInstance, setHostConfig, setMachineDeps } from '../../../packages/dsh-tauri-remote/src/host/config/runtime'
+import { events } from '../../../packages/dsh-tauri-remote/src/host/service/events'
+import { machine } from '../../../packages/dsh-tauri-remote/src/host/service/machine'
+import { sshTransport } from '../../../packages/dsh-tauri-remote/src/host/service/transport.ssh'
+import { MachineId } from '../../../packages/dsh-tauri-remote/src/host/types/index'
+import { EMPTY_ALLOWLIST } from '../../../packages/dsh-tauri-remote/src/host/utils/allowlist'
/** One timestamped evidence line. */
interface EvidenceLine {
@@ -65,9 +69,21 @@ function freshRsaPem(): string {
return String(privateKey.export({ format: 'pem', type: 'pkcs1' }))
}
+/**
+ * The minimal host context the runtime needs: the E2E suite drives the
+ * services directly, so nothing is ever registered on the web server and no
+ * effect is ever mounted.
+ */
+function hostContextStub(): RemoteHostContext {
+ return {
+ webServer: { register: () => () => {} },
+ effect: () => undefined,
+ }
+}
+
/** Every `it` leaves no runtime behind (assembly is process-global state). */
afterEach(() => {
- resetRuntime()
+ clearHostRuntime()
})
/**
@@ -76,7 +92,7 @@ afterEach(() => {
* with a timestamp.
*
* Assembly order is the production one (`apply.ts` is the only other caller):
- * reset the runtime → `setHostConfig` → `setMachineDeps`.
+ * clear the runtime → bind the host instance → `setHostConfig` → `setMachineDeps`.
*/
function bootHarness(options: {
connectTimeoutMs?: number
@@ -126,7 +142,8 @@ function bootHarness(options: {
console.log(`[+${(line.at - t0).toString().padStart(6)}ms] ${text}`)
}
- resetRuntime()
+ clearHostRuntime()
+ setCurrentHostInstance(hostContextStub())
setHostConfig({
connectTimeoutMs: options.connectTimeoutMs ?? 15_000,
healthCheckTimeoutMs: 3_000,
@@ -145,7 +162,7 @@ function bootHarness(options: {
statePath: join(root, 'machines.json'),
})
setMachineDeps({
- transport,
+ transport: { resolve: () => sshTransport },
emitStatus: (statusId, status) => {
const hints = [
status.state,
@@ -169,7 +186,7 @@ function bootHarness(options: {
clearInterval(poller)
drain()
await machine.dispose()
- resetRuntime()
+ clearHostRuntime()
rmSync(root, { recursive: true, force: true })
},
}
@@ -694,7 +711,7 @@ describe('e2e keepalive watchdog (silent connection freeze)', () => {
keepaliveCountMax: KEEPALIVE_COUNT_MAX,
sshDir: scratchSshDir,
})
- let session: SshSession | undefined
+ let session: RemoteSession | undefined
try {
harness.manager.refreshProfiles(new Map([[profile.id, profile]]))
const opened = await harness.manager.openSession(profile.id)
@@ -727,3 +744,479 @@ describe('e2e keepalive watchdog (silent connection freeze)', () => {
}
}, 60_000)
})
+
+/**
+ * E2E #5 — 出站网关:干净 link、身份改写与 SSH 链路压缩,全部跑在真实 ssh2 协议往返上。
+ *
+ * 远端 DSH 用本机 HTTP 服务器顶替(`/?token=` 铸造会话 cookie,其余请求按 cookie 放行),
+ * SSH 服务端是回环 ssh2 协议服务器:exec 通道回答健康探测与启动 token 读取,direct-tcpip
+ * 通道把隧道流量转给那台 HTTP 服务器。客户端与 sshd 之间挂一枚计数代理,把「链路压缩是否
+ * 真的生效」量成字节数;压缩协商结果直接读服务端连接的 `_protocol._kex.negotiated`。
+ *
+ * 环境降级标注:真实远端 DSH 与真实公网隧道不在本环境内(无可用远端机),桌面临窗口内的
+ * 真实对话与断网重连属人工验收;本套只覆盖可自动化的出站契约。
+ */
+describe('e2e outbound gateway (loopback ssh2 protocol server)', () => {
+ const PASSWORD = 'e2e-outbound'
+ const TOKEN = 'tok-e2e-outbound'
+ const BULK_BYTES = 200 * 1024
+ const BULK = Buffer.alloc(BULK_BYTES, 0x41)
+ const BOOT_HTML = '<html><body><script>globalThis["__DSH_BOOT__"] = {"entries":[{"url":"/plugins/@deepseek-ai/dsh-client-ui-layout/client.js"}]};</script></body></html>'
+
+ interface RemoteRequest {
+ url: string
+ host: string | undefined
+ encoding: string | undefined
+ cookie: string | undefined
+ }
+
+ interface Upstream {
+ port: number
+ requests: RemoteRequest[]
+ close: () => Promise<void>
+ }
+
+ interface SshdState {
+ negotiated: string | undefined
+ commands: string[]
+ }
+
+ interface Sshd {
+ server: SshServer
+ port: number
+ state: SshdState
+ }
+
+ let sshd: Sshd
+ let plainSshd: Sshd
+ let sshdProxy: { port: number, close: () => void }
+ let plainProxy: { port: number, close: () => void }
+ let wireBytes = 0
+ let scratchSshDir = ''
+
+ /** 远端 DSH 的替身:按启动 token 铸造会话 cookie,其余请求必须带对 cookie 才放行。 */
+ async function startUpstream(port = 0): Promise<Upstream> {
+ const requests: RemoteRequest[] = []
+ const upgraded = new Set<Duplex>()
+ const server = createHttpServer((request, response) => {
+ const url = request.url ?? ''
+ requests.push({
+ url,
+ host: request.headers.host,
+ encoding: request.headers['accept-encoding'],
+ cookie: request.headers.cookie,
+ })
+ if (url.startsWith('/?token=')) {
+ if (url !== `/?token=${TOKEN}`) {
+ response.statusCode = 401
+ response.end('bad token')
+ return
+ }
+ response.setHeader('set-cookie', [`dsh-session=${TOKEN}; Path=/; HttpOnly`])
+ response.end('minted')
+ return
+ }
+ if (request.headers.cookie !== `dsh-session=${TOKEN}`) {
+ response.statusCode = 401
+ response.end('unauthorized')
+ return
+ }
+ if (url === '/bulk') {
+ response.setHeader('content-type', 'application/javascript')
+ response.end(BULK)
+ return
+ }
+ response.setHeader('content-type', 'text/html')
+ response.end('dsh-ok')
+ })
+ await new Promise<void>((resolve) => {
+ server.listen(port, '127.0.0.1', () => resolve())
+ })
+ server.on('upgrade', (request, socket) => {
+ // 升级后的 socket 已脱离 server 的连接跟踪,必须自己记账才能在收尾时销毁。
+ upgraded.add(socket)
+ socket.on('close', () => upgraded.delete(socket))
+ requests.push({
+ url: request.url ?? '',
+ host: request.headers.host,
+ encoding: request.headers['accept-encoding'],
+ cookie: request.headers.cookie,
+ })
+ acceptWebSocket(request, socket)
+ })
+ return {
+ port: (server.address() as { port: number }).port,
+ requests,
+ close: async () => {
+ for (const socket of upgraded)
+ socket.destroy()
+ upgraded.clear()
+ server.closeAllConnections()
+ await new Promise<void>((resolve) => {
+ server.close(() => resolve())
+ })
+ },
+ }
+ }
+
+ /** 远端 DSH 的 WebSocket 端点替身:同样要求会话 cookie,回显每一帧文本/二进制。 */
+ function acceptWebSocket(request: IncomingMessage, socket: Duplex): void {
+ const key = request.headers['sec-websocket-key']
+ if (request.headers.cookie !== `dsh-session=${TOKEN}` || typeof key !== 'string') {
+ socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n')
+ socket.destroy()
+ return
+ }
+ const accept = createHash('sha1').update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest('base64')
+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`)
+ echoFrames(socket)
+ }
+
+ /** 最小帧编解码:只认单帧文本/二进制与关闭帧,足以证明升级链路端到端可用。 */
+ function echoFrames(socket: Duplex): void {
+ let pending = Buffer.alloc(0)
+ socket.on('data', (chunk: Buffer) => {
+ pending = Buffer.concat([pending, chunk])
+ while (pending.length >= 2) {
+ const opcode = pending[0]! & 0x0F
+ const masked = (pending[1]! & 0x80) !== 0
+ let length = pending[1]! & 0x7F
+ let offset = 2
+ if (length === 126) {
+ if (pending.length < 4)
+ return
+ length = pending.readUInt16BE(2)
+ offset = 4
+ }
+ const maskLength = masked ? 4 : 0
+ if (pending.length < offset + maskLength + length)
+ return
+ const mask = masked ? pending.subarray(offset, offset + 4) : undefined
+ const payload = Buffer.from(pending.subarray(offset + maskLength, offset + maskLength + length))
+ if (mask !== undefined) {
+ for (let index = 0; index < payload.length; index++)
+ payload[index] = payload[index]! ^ mask[index % 4]!
+ }
+ pending = pending.subarray(offset + maskLength + length)
+ if (opcode === 0x8) {
+ socket.write(Buffer.from([0x88, 0x00]))
+ socket.end()
+ return
+ }
+ if (opcode === 0x1 || opcode === 0x2)
+ socket.write(frameOf(opcode, payload))
+ }
+ })
+ }
+
+ function frameOf(opcode: number, payload: Buffer): Buffer {
+ if (payload.length < 126)
+ return Buffer.concat([Buffer.from([0x80 | opcode, payload.length]), payload])
+ const extended = Buffer.alloc(2)
+ extended.writeUInt16BE(payload.length)
+ return Buffer.concat([Buffer.from([0x80 | opcode, 126]), extended, payload])
+ }
+
+ function echoOnce(socket: WebSocket, text: string): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('e2e: WebSocket 回显超时')), 15_000)
+ socket.addEventListener('open', () => socket.send(text))
+ socket.addEventListener('message', (event) => {
+ clearTimeout(timer)
+ resolve(String(event.data))
+ socket.close()
+ })
+ socket.addEventListener('error', () => {
+ clearTimeout(timer)
+ reject(new Error('e2e: WebSocket 升级失败'))
+ })
+ })
+ }
+
+ /**
+ * 回环 ssh2 协议服务器。`compressAlgorithms` 省略即 ssh2 默认(服务端偏好 `none`,
+ * 但按 RFC 4253 由客户端的优先序决定结果);传 `['none']` 即「服务端不支持延迟压缩」。
+ */
+ async function startSshd(compressAlgorithms?: ['none']): Promise<Sshd> {
+ const state: SshdState = { negotiated: undefined, commands: [] }
+ const server = new Server(
+ {
+ hostKeys: [freshRsaPem()],
+ ...compressAlgorithms === undefined ? {} : { algorithms: { compress: compressAlgorithms } },
+ },
+ (client: Connection) => {
+ client.on('authentication', (ctx) => {
+ if (ctx.method === 'password' && ctx.password === PASSWORD) {
+ ctx.accept()
+ return
+ }
+ ctx.reject(['publickey', 'password'])
+ })
+ client.on('ready', () => {
+ const kex = (client as unknown as {
+ _protocol?: { _kex?: { negotiated?: { cs?: { compress?: string } } } }
+ })._protocol?._kex
+ state.negotiated = kex?.negotiated?.cs?.compress
+ })
+ client.on('session', (accept) => {
+ const session = accept()
+ session.on('exec', (acceptExec, _rejectExec, info) => {
+ const stream = acceptExec()
+ const command = (info as { command?: string }).command ?? ''
+ state.commands.push(command)
+ if (command.includes('grep -oE') && command.includes('token=')) {
+ stream.write(`${TOKEN}\n`)
+ stream.exit(0)
+ stream.end()
+ return
+ }
+ if (command.includes('%{http_code}')) {
+ stream.write('console.log(1)\n200')
+ stream.exit(0)
+ stream.end()
+ return
+ }
+ if (command.includes('curl -s -m')) {
+ stream.write(BOOT_HTML)
+ stream.exit(0)
+ stream.end()
+ return
+ }
+ stream.stderr.write('e2e: 未实现的远端命令\n')
+ stream.exit(1)
+ stream.end()
+ })
+ })
+ client.on('tcpip', (accept, _reject, info) => {
+ const channel = accept()
+ const dest = tcpConnect((info as { destPort: number }).destPort, '127.0.0.1')
+ channel.pipe(dest).pipe(channel)
+ channel.on('close', () => dest.destroy())
+ dest.on('error', () => channel.close())
+ })
+ client.on('error', () => {
+ // 断连与杀上游都由客户端侧发起,服务端只收尾。
+ })
+ },
+ )
+ await new Promise<void>((resolve) => {
+ server.listen(0, '127.0.0.1', () => resolve())
+ })
+ return { server, port: (server.address() as { port: number }).port, state }
+ }
+
+ /** 计数代理:客户端连它,它连 sshd;两个方向的字节都计入 `wireBytes`。 */
+ function startProxy(target: number): Promise<{ port: number, close: () => void }> {
+ const proxy = createServer((down) => {
+ const up = tcpConnect(target, '127.0.0.1')
+ down.on('data', (chunk: Buffer) => {
+ wireBytes += chunk.length
+ })
+ up.on('data', (chunk: Buffer) => {
+ wireBytes += chunk.length
+ })
+ down.pipe(up).pipe(down)
+ down.on('error', () => down.destroy())
+ up.on('error', () => up.destroy())
+ })
+ return new Promise((resolve) => {
+ proxy.listen(0, '127.0.0.1', () => resolve({
+ port: (proxy.address() as { port: number }).port,
+ close: () => proxy.close(),
+ }))
+ })
+ }
+
+ function profileFor(port: number, remotePort: number): MachineProfile {
+ return {
+ id: id('outbound-gateway'),
+ name: 'outbound-gateway',
+ host: '127.0.0.1',
+ port,
+ user: 'root',
+ password: PASSWORD,
+ remotePort,
+ }
+ }
+
+ beforeAll(async () => {
+ sshd = await startSshd()
+ plainSshd = await startSshd(['none'])
+ sshdProxy = await startProxy(sshd.port)
+ plainProxy = await startProxy(plainSshd.port)
+ scratchSshDir = mkdtempSync(join(tmpdir(), 'dsh-ssh-e2e-gateway-'))
+ writeFileSync(join(scratchSshDir, 'config'), '')
+ })
+
+ afterAll(() => {
+ sshd.server.close()
+ plainSshd.server.close()
+ sshdProxy.close()
+ plainProxy.close()
+ rmSync(scratchSshDir, { recursive: true, force: true })
+ })
+
+ it('publishes a credential-free loopback link and proxies a real request through the gateway', async () => {
+ const upstream = await startUpstream()
+ const harness = bootHarness({ sshDir: scratchSshDir, connectTimeoutMs: 5_000 })
+ try {
+ const profile = profileFor(sshdProxy.port, upstream.port)
+ harness.manager.refreshProfiles(new Map([[profile.id, profile]]))
+ const link = await harness.manager.connect(profile.id)
+ expect(link.tunnelBaseUrl, `link 必须是无凭据的回环入口,实际 ${link.tunnelBaseUrl}`).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/u)
+ expect(link.tunnelBaseUrl).not.toContain('token')
+ expect(harness.manager.status(profile.id).state).toBe('connected')
+ harness.log(`connected link=${link.tunnelBaseUrl}`)
+
+ const response = await fetch(link.tunnelBaseUrl)
+ const gatewayPort = new URL(link.tunnelBaseUrl).port
+ harness.log(`remote instance saw ${JSON.stringify(upstream.requests)}`)
+ expect(response.status).toBe(200)
+ expect(await response.text()).toBe('dsh-ok')
+ expect(upstream.requests.map(record => record.url)).toEqual([`/?token=${TOKEN}`, '/'])
+ expect(upstream.requests[1]?.cookie).toBe(`dsh-session=${TOKEN}`)
+ expect(upstream.requests[1]?.host).toBe(`127.0.0.1:${gatewayPort}`)
+ expect(upstream.requests[1]?.encoding).toBe('identity')
+ expect(upstream.requests[1]?.url).toBe('/')
+ }
+ finally {
+ await harness.dispose()
+ await upstream.close()
+ }
+ }, 90_000)
+
+ it('negotiates [email protected] and shrinks the tunnel bytes for a compressible body', async () => {
+ const upstream = await startUpstream()
+ const harness = bootHarness({ sshDir: scratchSshDir, connectTimeoutMs: 5_000 })
+ try {
+ // 协商结果记在服务端连接上且跨用例存活:本用例的断言必须由本用例的连接满足
+ sshd.state.negotiated = undefined
+ plainSshd.state.negotiated = undefined
+ const profile = profileFor(sshdProxy.port, upstream.port)
+ harness.manager.refreshProfiles(new Map([[profile.id, profile]]))
+ const link = await harness.manager.connect(profile.id)
+ expect(sshd.state.negotiated).toBe('[email protected]')
+ harness.log(`sshd negotiated compress=${String(sshd.state.negotiated)}`)
+
+ wireBytes = 0
+ const response = await fetch(`${link.tunnelBaseUrl}/bulk`)
+ const body = await response.text()
+ expect(response.status).toBe(200)
+ expect(body.length).toBe(BULK_BYTES)
+ harness.log(`wire ${wireBytes} bytes for a ${BULK_BYTES}-byte body`)
+ expect(wireBytes).toBeLessThan(BULK_BYTES / 5)
+ }
+ finally {
+ await harness.dispose()
+ await upstream.close()
+ }
+ }, 90_000)
+
+ it('degrades silently to no compression when the server does not offer it', async () => {
+ const upstream = await startUpstream()
+ const harness = bootHarness({ sshDir: scratchSshDir, connectTimeoutMs: 5_000 })
+ try {
+ plainSshd.state.negotiated = undefined
+ const profile = profileFor(plainProxy.port, upstream.port)
+ harness.manager.refreshProfiles(new Map([[profile.id, profile]]))
+ const link = await harness.manager.connect(profile.id)
+ expect(plainSshd.state.negotiated).toBe('none')
+ harness.log(`sshd negotiated compress=${String(plainSshd.state.negotiated)}`)
+
+ wireBytes = 0
+ const response = await fetch(`${link.tunnelBaseUrl}/bulk`)
+ const body = await response.text()
+ expect(response.status).toBe(200)
+ expect(body.length).toBe(BULK_BYTES)
+ harness.log(`wire ${wireBytes} bytes for a ${BULK_BYTES}-byte body without link compression`)
+ expect(wireBytes).toBeGreaterThan(BULK_BYTES)
+ }
+ finally {
+ await harness.dispose()
+ await upstream.close()
+ }
+ }, 90_000)
+
+ it('reuses the gateway port across a disconnect so the link survives a reconnect', async () => {
+ const upstream = await startUpstream()
+ const harness = bootHarness({ sshDir: scratchSshDir, connectTimeoutMs: 5_000 })
+ try {
+ const profile = profileFor(sshdProxy.port, upstream.port)
+ harness.manager.refreshProfiles(new Map([[profile.id, profile]]))
+ const first = await harness.manager.connect(profile.id)
+ await harness.manager.disconnect(profile.id)
+ expect(harness.manager.status(profile.id).state).toBe('disconnected')
+ const again = await harness.manager.connect(profile.id)
+ expect(again.tunnelBaseUrl).toBe(first.tunnelBaseUrl)
+ harness.log(`rebound the same gateway port ${again.tunnelBaseUrl}`)
+ expect((await fetch(again.tunnelBaseUrl)).status).toBe(200)
+ }
+ finally {
+ await harness.dispose()
+ await upstream.close()
+ }
+ }, 90_000)
+
+ it('keeps the link and the SSH session when the remote instance dies, and serves it again once the instance is back', async () => {
+ const upstream = await startUpstream()
+ const port = upstream.port
+ const harness = bootHarness({ sshDir: scratchSshDir, connectTimeoutMs: 5_000, reconnectInitialDelayMs: 300, reconnectMaxAttempts: 4 })
+ let live = upstream
+ try {
+ const profile = profileFor(sshdProxy.port, port)
+ harness.manager.refreshProfiles(new Map([[profile.id, profile]]))
+ const link = await harness.manager.connect(profile.id)
+ expect((await fetch(link.tunnelBaseUrl)).status).toBe(200)
+
+ // 只杀远端实例:隧道口(SSH 转发监听口)仍在,链路没有断,因此禁止重拨与换 link
+ await live.close()
+ const response = await fetch(link.tunnelBaseUrl)
+ expect(response.status).toBe(502)
+ await waitFor(() => (harness.manager.status(profile.id).lastError ?? '').includes('上游不可达'), 'readable per-request failure')
+ expect(harness.manager.status(profile.id).state).toBe('connected')
+ harness.log(`observed a per-request failure while still connected: ${harness.manager.status(profile.id).lastError}`)
+
+ live = await startUpstream(port)
+ const deadline = Date.now() + 30_000
+ let resumed = await fetch(link.tunnelBaseUrl)
+ while (resumed.status !== 200 && Date.now() < deadline) {
+ await new Promise(resolve => setTimeout(resolve, 100))
+ resumed = await fetch(link.tunnelBaseUrl)
+ }
+ expect(resumed.status).toBe(200)
+ expect(harness.manager.status(profile.id).state).toBe('connected')
+ expect(harness.manager.link(profile.id)?.tunnelBaseUrl).toBe(link.tunnelBaseUrl)
+ harness.log(`link serves again at the SAME ${link.tunnelBaseUrl} without a reconnect`)
+ }
+ finally {
+ await live.close()
+ await harness.dispose()
+ }
+ }, 120_000)
+
+ it('carries a WebSocket upgrade end to end through the outbound gateway', async () => {
+ const upstream = await startUpstream()
+ const harness = bootHarness({ sshDir: scratchSshDir, connectTimeoutMs: 5_000 })
+ try {
+ const profile = profileFor(sshdProxy.port, upstream.port)
+ harness.manager.refreshProfiles(new Map([[profile.id, profile]]))
+ const link = await harness.manager.connect(profile.id)
+ const gatewayPort = new URL(link.tunnelBaseUrl).port
+
+ // 全部 RPC 与对话流都跑在这条 WebSocket 上:升级链路必须端到端可用
+ const echoUrl = `${link.tunnelBaseUrl.replace(/^http/u, 'ws')}/api/remote.mux`
+ const echoed = await echoOnce(new WebSocket(echoUrl), 'ping-through-tunnel')
+ expect(echoed).toBe('ping-through-tunnel')
+
+ const upgrade = upstream.requests.find(record => record.url === '/api/remote.mux')
+ expect(upgrade, '远端替身必须收到升级请求').toBeDefined()
+ expect(upgrade?.cookie, '升级请求同样由网关注入铸造出的会话 cookie').toBe(`dsh-session=${TOKEN}`)
+ expect(upgrade?.host).toBe(`127.0.0.1:${gatewayPort}`)
+ harness.log(`upgraded through ${link.tunnelBaseUrl} and echoed a frame`)
+ }
+ finally {
+ await harness.dispose()
+ await upstream.close()
+ }
+ }, 90_000)
+})
diff --git a/test/e2e/setup-plugin.ts b/test/e2e/setup-plugin.ts
index a4ace0ab..9c52a7ea 100644
--- a/test/e2e/setup-plugin.ts
+++ b/test/e2e/setup-plugin.ts
@@ -48,6 +48,7 @@ const DEFAULT_ALSO = [
'dsh-tauri-scheduler',
'dsh-tauri-experimental',
'dsh-tauri-model',
+ 'dsh-tauri-remote',
].join(',')
export default async function setup(project: TestProject): Promise<() => Promise<void>> {
diff --git a/test/remote-contract.test.ts b/test/remote-contract.test.ts
new file mode 100644
index 00000000..e9b13b7a
--- /dev/null
+++ b/test/remote-contract.test.ts
@@ -0,0 +1,223 @@
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { describe, expect, it } from 'vitest'
+import { PLUGIN_ID, REMOTE_TAB_ACCESS as PLUGIN_TAB_ACCESS, REMOTE_TAB_MACHINES as PLUGIN_TAB_MACHINES, REMOTE_TAB_SYNC as PLUGIN_TAB_SYNC, SETTINGS_SECTION_ID } from '../packages/dsh-tauri-remote/src/client/constants/index'
+import { REMOTE_SECTION, REMOTE_TAB_ACCESS, REMOTE_TAB_MACHINES, REMOTE_TAB_SYNC } from '../src/layout/components/nav-bridge'
+
+const ROOT = resolve(import.meta.dirname, '..')
+const PLUGIN = 'dsh-tauri-remote'
+const PREFIX = `/api/tauri/${PLUGIN.replace('dsh-tauri-', '')}`
+
+const HOST_ROUTES = 'packages/dsh-tauri-remote/src/host/server/index.ts'
+const PANEL_ROUTES = 'packages/dsh-tauri-remote/src/host/server/panel.ts'
+const RUST_BRIDGE = 'src-tauri/src/bridge/remote.rs'
+const SHELL_API = 'src/apis/remote.ts'
+const PLUGIN_API = 'packages/dsh-tauri-remote/src/client/apis/index.ts'
+const PLUGIN_API_TYPES = 'packages/dsh-tauri-remote/src/client/apis/index.type.ts'
+const EVENTS_ROUTE = 'packages/dsh-tauri-remote/src/host/server/routes/machines/events/get.ts'
+const SHELL_API_TYPES = 'src/apis/remote.types.ts'
+const ACCESS_GET = 'packages/dsh-tauri-remote/src/host/server/routes/access/get.ts'
+const ACCESS_UTILS = 'packages/dsh-tauri-remote/src/host/service/access.utils.ts'
+
+function source(relative: string): string {
+ return readFileSync(resolve(ROOT, relative), 'utf8')
+}
+
+/** 从 `app.<verb>('<path>', handler)` 逐条取注册表的「方法 + 路径」;路径是字面量,不从插件名派生。 */
+function hostRoutes(relative: string): string[] {
+ const pattern = /app\.(get|post|put|delete|patch)\('([^']+)'/g
+ return [...source(relative).matchAll(pattern)].map(match => `${match[1].toUpperCase()} ${match[2]}`)
+}
+
+/** 从 `ofetch<T>("<path>", { method: "<verb>" })` 取生成客户端的「方法 + 完整 URL」。 */
+function clientCalls(relative: string): string[] {
+ const pattern = /ofetch<[^>]+>\("([^"]+)",\s*\{\s*method:\s*"(\w+)"/g
+ return [...source(relative).matchAll(pattern)].map(match => `${match[2].toUpperCase()} ${match[1]}`)
+}
+
+function exportedApiNames(relative: string): string[] {
+ return [...source(relative).matchAll(/export function (\w+)\(/g)].map(match => match[1])
+}
+
+/** Rust 里出现的全部 `"<VERB> /api/tauri/…"` 字面量:生产 match、单测允许列表与负例共用同一文件。 */
+function rustEndpointLiterals(): string[] {
+ return [...source(RUST_BRIDGE).matchAll(/"((?:GET|POST|DELETE|PUT|PATCH) \/api\/tauri\/[^"]*)"/g)].map(match => match[1])
+}
+
+/** 生成客户端里 `params?: Types.<X>` 引用的具名查询契约。 */
+function queryTypeNames(): string[] {
+ return [...source(PLUGIN_API).matchAll(/params\?: Types\.(\w+)/g)].map(match => match[1])
+}
+
+const EXPECTED_ENDPOINTS = [
+ `POST ${PREFIX}/machines/connect`,
+ `GET ${PREFIX}/machines`,
+ `POST ${PREFIX}/machines`,
+ `DELETE ${PREFIX}/machines`,
+ `POST ${PREFIX}/machines/disconnect`,
+ `GET ${PREFIX}/machines/events`,
+ `POST ${PREFIX}/machines/install`,
+ `POST ${PREFIX}/machines/test`,
+ `GET ${PREFIX}/session/role`,
+ `GET ${PREFIX}/settings`,
+ `POST ${PREFIX}/settings`,
+ `POST ${PREFIX}/sync/apply`,
+ `GET ${PREFIX}/sync/preview`,
+ `GET ${PREFIX}/access`,
+ `POST ${PREFIX}/access`,
+ `POST ${PREFIX}/access/tunnel`,
+ `DELETE ${PREFIX}/access/tunnel`,
+]
+
+const HOST_ROUTE_ORDER = [
+ `GET ${PREFIX}/settings`,
+ `POST ${PREFIX}/settings`,
+ `GET ${PREFIX}/session/role`,
+ `GET ${PREFIX}/machines`,
+ `POST ${PREFIX}/machines`,
+ `DELETE ${PREFIX}/machines`,
+ `POST ${PREFIX}/machines/test`,
+ `POST ${PREFIX}/machines/connect`,
+ `POST ${PREFIX}/machines/disconnect`,
+ `POST ${PREFIX}/machines/install`,
+ `GET ${PREFIX}/machines/events`,
+ `GET ${PREFIX}/sync/preview`,
+ `POST ${PREFIX}/sync/apply`,
+ `GET ${PREFIX}/access`,
+ `POST ${PREFIX}/access`,
+ `POST ${PREFIX}/access/tunnel`,
+ `DELETE ${PREFIX}/access/tunnel`,
+]
+
+/**
+ * 面板专用入口:只在 `server/panel.ts` 登记,由面板 iframe 同源 fetch 消费,
+ * **不进**桌面壳白名单与两份生成客户端;新增这类路由必须在此显式登记。
+ *
+ * 只保留完整凭据管理(生成 / 撤销永久码)——入站分享(`/access`、`/access/tunnel`)
+ * 由桌面壳的分享弹层直接调用,因此登记在管理表与白名单里。
+ */
+const ACCESS_ROUTE_ORDER = [
+ `POST ${PREFIX}/access/token`,
+ `DELETE ${PREFIX}/access/token`,
+]
+
+describe('shell ↔ plugin identity contract', () => {
+ it('the shell settings section id is the plugin id the section registers under', () => {
+ expect(REMOTE_SECTION).toBe(PLUGIN_ID)
+ expect(SETTINGS_SECTION_ID).toBe(PLUGIN_ID)
+ expect(PLUGIN_ID).toBe(PLUGIN)
+ })
+
+ it('the shell deep-link tabs are the tabs the plugin keys its panels by', () => {
+ expect([REMOTE_TAB_MACHINES, REMOTE_TAB_SYNC, REMOTE_TAB_ACCESS]).toEqual([PLUGIN_TAB_MACHINES, PLUGIN_TAB_SYNC, PLUGIN_TAB_ACCESS])
+ })
+
+ it('both generated clients inline the plugin prefix on every call', () => {
+ const shell = clientCalls(SHELL_API)
+ expect(shell.length).toBeGreaterThan(0)
+ for (const call of shell)
+ expect(call).toContain(`${PREFIX}/`)
+ for (const call of clientCalls(PLUGIN_API))
+ expect(call).toContain(`${PREFIX}/`)
+ })
+})
+
+describe('17-endpoint agreement across the four lists', () => {
+ it('the management route table declares exactly the 17 endpoints', () => {
+ expect(hostRoutes(HOST_ROUTES)).toEqual(HOST_ROUTE_ORDER)
+ })
+
+ it('the panel route table declares exactly the exposed access endpoints', () => {
+ expect(hostRoutes(PANEL_ROUTES)).toEqual(ACCESS_ROUTE_ORDER)
+ })
+
+ it('the shell and plugin generated clients cover exactly the management route table', () => {
+ expect([...clientCalls(SHELL_API)].sort()).toEqual([...EXPECTED_ENDPOINTS].sort())
+ expect([...clientCalls(PLUGIN_API)].sort()).toEqual([...EXPECTED_ENDPOINTS].sort())
+ })
+
+ it('neither generated client nor the rust bridge carries a panel-only route', () => {
+ for (const route of ACCESS_ROUTE_ORDER) {
+ expect(clientCalls(SHELL_API)).not.toContain(route)
+ expect(clientCalls(PLUGIN_API)).not.toContain(route)
+ expect(rustEndpointLiterals()).not.toContain(route)
+ }
+ })
+
+ it('the rust desktop bridge whitelists exactly the management route table', () => {
+ const literals = rustEndpointLiterals()
+ const whitelisted = [...new Set(literals)].filter(literal => EXPECTED_ENDPOINTS.includes(literal))
+ expect(whitelisted.sort()).toEqual([...EXPECTED_ENDPOINTS].sort())
+ // 生产 match 与单测的允许列表各写一次;负例(PUT、大小写、多余查询、换行)不引入新端点。
+ for (const endpoint of EXPECTED_ENDPOINTS)
+ expect(literals.filter(literal => literal === endpoint).length, endpoint).toBeGreaterThanOrEqual(2)
+ })
+
+ it('every plugin generated function is named after its route file path', () => {
+ expect([...exportedApiNames(PLUGIN_API)].sort()).toEqual([...[
+ 'postMachinesConnect',
+ 'getMachines',
+ 'postMachines',
+ 'deleteMachines',
+ 'postMachinesDisconnect',
+ 'getMachinesEvents',
+ 'postMachinesInstall',
+ 'postMachinesTest',
+ 'getSessionRole',
+ 'getSettings',
+ 'postSettings',
+ 'postSyncApply',
+ 'getSyncPreview',
+ 'getAccess',
+ 'postAccess',
+ 'postAccessTunnel',
+ 'deleteAccessTunnel',
+ ]].sort())
+ expect(exportedApiNames(PLUGIN_API)).toHaveLength(EXPECTED_ENDPOINTS.length)
+ expect(exportedApiNames(SHELL_API)).toEqual(exportedApiNames(PLUGIN_API))
+ })
+
+ it('the generated query contracts are the ones the route handlers declare', () => {
+ expect(queryTypeNames()).toEqual(['GetApiTauriRemoteMachinesEventsQuery', 'GetApiTauriRemoteAccessQuery'])
+ expect(source(EVENTS_ROUTE)).toContain('GetMachinesEventsQuery')
+ expect(source(ACCESS_GET)).toContain('getQuery<GetAccessQuery>(event)')
+ for (const file of [SHELL_API_TYPES, PLUGIN_API_TYPES]) {
+ expect(source(file), file).toContain('export interface GetApiTauriRemoteMachinesEventsQuery {')
+ expect(source(file), file).toContain('export interface GetApiTauriRemoteAccessQuery {')
+ expect(source(file), file).toContain('sincePairingUseSeq?: GetApiTauriRemoteAccessQuerySincePairingUseSeq;')
+ expect(source(file), file).toContain('export type GetApiTauriRemoteAccessQuerySincePairingUseSeq = number;')
+ expect(source(file), file).toContain('usedSeq: number')
+ }
+ })
+
+ it('no stale ssh identifier survives in either generated client', () => {
+ expect(source(SHELL_API)).not.toMatch(/ssh/i)
+ expect(source(PLUGIN_API)).not.toMatch(/ssh/i)
+ expect(source(PLUGIN_API_TYPES)).not.toMatch(/ssh/i)
+ })
+})
+
+describe('loopback credential contract', () => {
+ it('both generated clients type the credential as an optional field', () => {
+ for (const file of [SHELL_API_TYPES, PLUGIN_API_TYPES])
+ expect(source(file), file).toContain('hasToken?: false | true; token?: string')
+ })
+
+ it('both routers enforce the same local-only management guard before registering routes', () => {
+ for (const file of [HOST_ROUTES, PANEL_ROUTES]) {
+ const router = source(file)
+ const native = router.indexOf('app.use(guard)')
+ const local = router.indexOf('app.use(remoteSourceGuard)')
+ const firstRoute = router.search(/app\.(?:get|post|delete)\(/u)
+ expect(native, file).toBeGreaterThanOrEqual(0)
+ expect(local, file).toBeGreaterThan(native)
+ expect(firstRoute, file).toBeGreaterThan(local)
+ }
+ })
+
+ it('redaction keeps the presence flag and drops the credential', () => {
+ const redact = source(ACCESS_UTILS).match(/function redactStatus[\s\S]*?\n\}/)?.[0] ?? ''
+ expect(redact).toContain('hasToken')
+ expect(redact).not.toContain('token:')
+ })
+})
diff --git a/test/tooling-config.test.ts b/test/tooling-config.test.ts
index 85b9e816..4773b503 100644
--- a/test/tooling-config.test.ts
+++ b/test/tooling-config.test.ts
@@ -108,8 +108,8 @@ describe('tooling configuration contracts', () => {
['archive/contract.test.ts', []],
['source/contract.test.ts', []],
['packages/dsh-tauri/node_modules/copy/index.test.ts', []],
- ['packages/dsh-tauri-ssh/src/client/components/panel.test.tsx', ['unit']],
- ['packages/dsh-tauri-ssh/src/client/index.test.ts', ['unit']],
+ ['packages/dsh-tauri-remote/src/client/components/panel.test.tsx', ['unit']],
+ ['packages/dsh-tauri-remote/src/client/index.test.ts', ['unit']],
['src/layout/components/remote-switcher.test.tsx', ['unit']],
['src/layout/components/connect-dialog.test.tsx', ['unit']],
] as const
@@ -121,8 +121,8 @@ describe('tooling configuration contracts', () => {
expect(specs.filter(spec => spec.moduleId.endsWith('/test/e2e/desktop/boot.e2e.ts')).map(spec => spec.project.name)).toEqual(['desktop'])
expect(specs.filter(spec => spec.moduleId.endsWith('/test/e2e/plugins/dsh-tauri.e2e.ts')).map(spec => spec.project.name)).toEqual(['plugin'])
for (const file of [
- 'packages/dsh-tauri-ssh/src/client/components/machines-section.test.tsx',
- 'packages/dsh-tauri-ssh/src/client/index.test.ts',
+ 'packages/dsh-tauri-remote/src/client/components/machines-section.test.tsx',
+ 'packages/dsh-tauri-remote/src/client/index.test.ts',
'src/layout/components/remote-switcher.test.tsx',
'src/layout/components/connect-dialog.test.tsx',
]) {