提交记录修改README.md+1 −1看文件
修改docs/guide/tailscale.md+38 −22看文件
修改internal/cage/tailnet-client.mjs+3 −2看文件
修改internal/cage/tailnet-client.test.mjs+9 −0看文件
修改internal/workbench/tailnet.go+14 −3看文件
修改internal/workbench/tailnet_test.go+33 −0看文件
修改tools/tailnet/dial.go+17 −36看文件
修改tools/tailnet/main.go+75 −23看文件
修改tools/tailnet/main_test.go+13 −1看文件
新增tools/tailnet/network.go+160 −0看文件
新增tools/tailnet/network_forward.go+144 −0看文件
新增tools/tailnet/network_test.go+297 −0看文件
新增tools/tailnet/status_test.go+37 −0看文件
修改ui/scripts/tailscale-smoke.mjs+79 −26看文件
修改ui/src/main.jsx+1 −1看文件
修改ui/src/tailscale.css+66 −14看文件
修改ui/src/tailscale.jsx+113 −50看文件
| @@ -45,7 +45,7 @@ Claude Cage 让你在熟悉的系统里与 Claude 一起工作:Mac 上用 macO | ||
| 45 | 45 | - **管理多个 Claude Code 订阅。** 查看额度、为新会话分配账号,并在明确授权后切换账号接续历史。 [Claude Code](docs/guide/accounts.md) |
| 46 | 46 | - **从手机继续处理任务。** Android / iPhone 配对电脑,接续 Claude Code 对话与工具审批,或操作远程浏览器和 Claude Desktop。[手机连接](docs/guide/mobile.md) |
| 47 | 47 | - **把环境放到自己的服务器。** 通过 SSH 部署或连接 Linux VPS,工具、任务和数据留在服务器,无需 KVM。[云端部署与 SSH](docs/guide/cloud.md) |
| 48 | 删除:- **通过私网连接。** 在 Cage 内登录 Tailscale,让本机与环境通过 SSH 双向连接。 [Tailscale / SSH](docs/guide/tailscale.md) | |
| 48 | 新增:- **通过私网连接设备。** 在 Cage 内登录 Tailscale,查看网络中的设备,使用 SSH、Web 与其他 TCP 服务。 [Tailscale 私网](docs/guide/tailscale.md) | |
| 49 | 49 | |
| 50 | 50 | 浏览器收藏、无痕会话、Cookie、扩展、密码保险箱,以及外观、资源、存储和工具更新,见[完整使用文档](https://lee-xeo.github.io/Claude-Cage/docs/)。 |
| 51 | 51 | |
| @@ -1,47 +1,63 @@ | ||
| 1 | 1 | --- |
| 2 | 删除:title: Tailscale 与 SSH 私网 | |
| 3 | 删除:description: 在 Cage 浏览器登录 Tailscale,让本机和 Cage 环境通过私网双向 SSH。 | |
| 2 | 新增:title: Tailscale 私网 | |
| 3 | 新增:description: 登录 Tailscale,让 Cage 加入自己的私网,查看设备并连接 SSH、Web 与其他 TCP 服务。 | |
| 4 | 4 | group: 日常工作 |
| 5 | 5 | order: 6.5 |
| 6 | 删除:keywords: Tailscale tailnet SSH 公钥 私网 本机 远程登录 SFTP | |
| 6 | 新增:keywords: Tailscale tailnet 设备 私网 SSH Web TCP 代理 | |
| 7 | 7 | --- |
| 8 | 8 | |
| 9 | 删除:## 连接 Cage 与本机 | |
| 9 | 新增:## 登录并加入私网 | |
| 10 | 10 | |
| 11 | 删除:左侧栏的「Tailscale」位于「浏览器」下方。它为当前 Cage 环境提供独立的 Tailscale 设备身份,登录状态保存在客机磁盘中。本机也需要安装 Tailscale,并加入同一网络。 | |
| 11 | 新增:工作台左侧「浏览器」下方的「Tailscale」,用于将当前 Cage 环境作为一台独立设备加入你的 Tailscale 网络。登录状态保存在客机磁盘中,关闭面板不会断开连接。本机、手机或服务器也需要安装 Tailscale,并加入同一网络。 | |
| 12 | 12 | |
| 13 | 删除:启动 Cage 环境后打开此面板。Debian 环境首次使用时点击「安装 Tailscale」;macOS、Windows 环境的组件随应用提供,已有环境可按面板提示更新环境组件。点击「连接 Tailscale」,在 Cage 浏览器打开的官方页面完成授权。返回面板即可查看连接状态、Cage 私网地址和其他设备。网络启用设备审批时,还需由该网络的管理员批准设备。 | |
| 13 | 新增:启动 Cage 环境,打开 Tailscale 面板,点击「连接并登录」。在打开的官方授权页面完成登录,然后重新打开 Tailscale 面板。连接成功后,可看到当前账号、网络名称、Cage 的私网地址与设备清单。网络要求设备审批时,面板显示「等待管理员批准」,由网络管理员在 Tailscale 管理台批准 Cage 后即可继续。 | |
| 14 | 14 | |
| 15 | 删除:当前开发构建已通过隔离私网中的双向 SSH、SFTP、端口转发和身份保留验证。真实 Tailscale 账号授权、安装环境与本机的实际双向连接,以及三类客机暂停后的断线仍待验收。公开安装包是否包含此入口,以对应发行说明为准。 | |
| 15 | 新增:Debian 环境首次使用时需点击「安装 Tailscale」。macOS 和 Windows 环境随客机组件提供,已有环境可按面板提示更新环境组件。 | |
| 16 | 16 | |
| 17 | 删除:## 从本机连接 Cage | |
| 17 | 新增:设备清单显示当前网络允许 Cage 发现的设备,在线设备排在前面,支持按名称、系统或私网地址搜索。清单为空时,先检查其他设备是否加入同一网络,以及网络的设备访问规则。 | |
| 18 | 18 | |
| 19 | 删除:在 Tailscale 面板的「本机连接 Cage」中粘贴本机 SSH 公钥并点击「添加公钥」。公钥通常位于本机的 `~/.ssh/id_ed25519.pub`;私钥保留在本机。面板接受一条公钥,不接受私钥或带有限制选项的 `authorized_keys` 条目。 | |
| 19 | 新增:## 使用设备上的服务 | |
| 20 | 20 | |
| 21 | 删除:连接成功后,面板显示实际客机用户名和私网地址,例如: | |
| 21 | 新增:在设备旁点击「使用设备」,按服务类型选择连接方式。设备在线表示它已连接 Tailscale,服务是否可用仍取决于目标设备是否启动该服务、端口和访问权限。 | |
| 22 | 22 | |
| 23 | 删除:```sh | |
| 24 | 删除:ssh [email protected] | |
| 25 | 删除:``` | |
| 23 | 新增:### Web、数据库与其他 TCP 服务 | |
| 24 | 新增: | |
| 25 | 新增:例如,服务器上的开发网站监听端口 `8080`:填写「服务端口」为 `8080`,点击「创建连接地址」。面板会给出类似 `127.0.0.1:32123` 的地址,在 Cage 内的应用中使用这个地址,即可连接到该设备的 `8080` 端口。HTTP 网站可直接点击「打开 HTTP 页面」。数据库客户端等应用填写此地址和对应端口,并按目标服务的要求认证。 | |
| 26 | 新增: | |
| 27 | 新增:这些地址只在当前 Cage 环境内生效,在宿主机打开同一个回环地址无法连接。映射不修改目标服务的登录方式。HTTPS 和其他要求目标域名与证书一致的服务,应使用下述私网代理,保留原目标域名和证书校验。 | |
| 28 | 新增: | |
| 29 | 新增:### 需要设备域名、HTTPS 或多个端口的应用 | |
| 30 | 新增: | |
| 31 | 新增:展开「应用访问私网」,点击「复制私网代理地址」,将其配置为 Cage 内应用的 HTTP 代理。代理支持 HTTP 和 HTTPS CONNECT,仅连接当前私网中可见的设备;请只为需要访问私网的应用配置它。该专用代理拒绝公网目标,不能用来替代应用原有的公网代理。 | |
| 26 | 32 | |
| 27 | 删除:在本机终端运行复制的命令。首次连接按 SSH 提示核对并保存服务端指纹。登录后获得当前 Cage 客机普通用户的权限,可使用交互终端、远程命令、SFTP 和 SSH 本地端口转发。SSH 服务仅在 Tailscale 网络监听,不开放主机公网或局域网端口。移除公钥会拒绝该密钥的新连接;断开 Tailscale 可结束已有私网连接。 | |
| 33 | 新增:复制的地址包含本地访问凭据,不要分享给他人。组件进程重启后需重新复制代理地址。 | |
| 28 | 34 | |
| 29 | 删除:## 从 Cage 连接本机 | |
| 35 | 新增:Cage 使用内嵌 Tailscale 节点。SSH 已自动配置私网传输,其他应用通过本地连接地址或 HTTP 代理访问 TCP 服务。系统 VPN、任意应用直接使用私网地址、UDP、子网路由和出口节点未启用。此功能不接管宿主机的 Tailscale 或系统网络。 | |
| 30 | 36 | |
| 31 | 删除:本机须开启操作系统的远程登录或 SSH 服务,并允许相应的 Tailscale 连接。在面板的设备列表找到本机,复制命令,将「本机用户名」替换为实际用户名,然后在 Cage 终端运行: | |
| 37 | 新增:### 从 Cage SSH 到其他设备 | |
| 38 | 新增: | |
| 39 | 新增:目标设备需开启远程登录或 SSH 服务。在「SSH 连接」中填写该设备的系统用户名,点击「复制 SSH 命令」,在 Cage 终端运行。认证使用目标 SSH 服务支持的密码或密钥,Cage 不会自动导入宿主机私钥。 | |
| 40 | 新增: | |
| 41 | 新增:普通 `ssh`、SFTP 和使用 OpenSSH 的工具,也可使用设备的私网 IPv4、完整名称或短名称。Cage 为已发现设备维护专用的 OpenSSH 传输配置,保留用户原有规则。 | |
| 42 | 新增: | |
| 43 | 新增:## 从其他设备 SSH 到 Cage | |
| 44 | 新增: | |
| 45 | 新增:仅在需要远程终端、SFTP 或编辑器连接时,展开「从其他设备 SSH 到 Cage」。将连接设备的 SSH 公钥添加到面板,私钥保留在原设备。面板接受一条公钥,不接受私钥或带有限制选项的 `authorized_keys` 条目。 | |
| 46 | 新增: | |
| 47 | 新增:复制面板给出的命令,在连接设备的终端运行,例如: | |
| 32 | 48 | |
| 33 | 49 | ```sh |
| 34 | 删除:ssh 本机用户名@100.88.2.4 | |
| 50 | 新增:ssh [email protected] | |
| 35 | 51 | ``` |
| 36 | 52 | |
| 37 | 删除:登录使用本机 SSH 服务支持的密码或密钥认证。Cage 不会导入本机私钥。通过 Tailscale 登录本身不会自动授予本机 SSH 权限。 | |
| 53 | 新增:首次连接时核对并保存 SSH 服务端指纹。登录后拥有当前 Cage 客机普通用户的权限,可使用交互终端、远程命令、SFTP 和 SSH 本地端口转发。移除公钥可拒绝该密钥的新连接;断开 Tailscale 可结束已有私网连接。 | |
| 38 | 54 | |
| 39 | 删除:Cage 会为已发现的私网设备维护客机 OpenSSH 配置,普通 `ssh`、SFTP 和使用 OpenSSH 的工具可按设备私网 IPv4、完整名称或短名称连接。这里使用标准 SSH 的认证方式;Tailscale 管理台的专用「Tailscale SSH」身份认证与这项公钥服务分别配置。 | |
| 55 | 新增:这里使用标准 SSH 公钥认证。Tailscale 专用的「Tailscale SSH」身份认证需另行配置,登录 Tailscale 本身不自动授予系统 SSH 权限。 | |
| 40 | 56 | |
| 41 | 57 | ## 断开、退出与数据保留 |
| 42 | 58 | |
| 43 | 删除:「断开连接」结束私网连接,保留登录状态、公钥和 SSH 服务端身份。重新连接沿用原设备。「退出登录」撤销当前登录,下次连接需要浏览器重新授权;已添加的 SSH 公钥保留。关闭面板不会断开连接。 | |
| 59 | 新增:「断开连接」结束私网连接与服务映射,保留登录状态、公钥和 SSH 服务端身份。重新连接沿用原设备;本地服务地址需要重新创建。「退出登录」撤销当前登录,下次连接需要浏览器重新授权,已添加的 SSH 公钥保留。 | |
| 44 | 60 | |
| 45 | 删除:私网外层通信继续经过 Cage 的受控出口。公网 UDP 受限时,Tailscale 使用中继传输。暂停 Cage 外网、代理中断、环境停止或后台退出会影响私网连接。保留环境运行时,后台任务与私网按环境生命周期继续;重新启动会恢复已启用的 Tailscale 身份。 | |
| 61 | 新增:私网外层通信继续经过 Cage 的受控出口。公网 UDP 受限时,Tailscale 通过中继传输。暂停 Cage 联网、代理中断、环境停止或后台退出会影响私网连接。环境重新启动后恢复已启用的 Tailscale 身份。 | |
| 46 | 62 | |
| 47 | 删除:Tailscale 的网络访问规则仍决定设备间哪些连接可达。此功能提供 SSH 私网访问,不修改 Cage 的公网代理、系统 DNS、子网路由或出口节点设置。SSH 连接到本机后,命令在本机执行,其权限和网络行为由本机管理。 | |
| 63 | 新增:设备间访问仍受 Tailscale 网络规则控制。连接到其他设备后,命令的权限和网络行为由目标设备管理。 | |
| @@ -32,13 +32,14 @@ export function createTailnetClient({ executable, launch, start = spawn } = {}) | ||
| 32 | 32 | return true; |
| 33 | 33 | } |
| 34 | 34 | async function run(input) { |
| 35 | 删除: if (!input || !["status", "connect", "login", "disconnect", "logout", "add-key", "remove-key"].includes(input.action) || typeof input.key !== "undefined" && (typeof input.key !== "string" || input.key.length > 8192)) throw new Error("Tailscale 操作无效"); | |
| 35 | 新增: if (!input || !["status", "connect", "login", "disconnect", "logout", "add-key", "remove-key", "open-service"].includes(input.action) || typeof input.key !== "undefined" && (typeof input.key !== "string" || input.key.length > 8192)) throw new Error("Tailscale 操作无效"); | |
| 36 | 新增: if (input.action === "open-service" && (typeof input.host !== "string" || !/^[a-zA-Z0-9.-]{1,253}$/.test(input.host) || !Number.isInteger(input.port) || input.port < 1 || input.port > 65535)) throw new Error("请选择私网设备并填写有效端口"); | |
| 36 | 37 | if (!await open()) return { installed: false, enabled: false, backend: "NotInstalled", ips: [], peers: [], keys: [] }; |
| 37 | 38 | return new Promise((resolve, reject) => { |
| 38 | 39 | const current = child; |
| 39 | 40 | const timer = setTimeout(() => { current.kill(); reject(new Error("Tailscale 暂未响应,请稍后重试")); }, 12000); |
| 40 | 41 | pending = { resolve: value => { clearTimeout(timer); resolve(value); }, reject: error => { clearTimeout(timer); reject(error); } }; |
| 41 | 删除: current.stdin.write(JSON.stringify({ action: input.action, ...(input.key === undefined ? {} : { key: input.key }) }) + "\n"); | |
| 42 | 新增: current.stdin.write(JSON.stringify({ action: input.action, ...(input.key === undefined ? {} : { key: input.key }), ...(input.action === "open-service" ? { host: input.host, port: input.port } : {}) }) + "\n"); | |
| 42 | 43 | }); |
| 43 | 44 | } |
| 44 | 45 | return { |
| @@ -20,3 +20,12 @@ test("missing guest payload offers installation without spawning a host VPN", as | ||
| 20 | 20 | const client=createTailnetClient({executable:"/nonexistent-cage-tailnet",start:()=>{throw Error("must not spawn")}}); |
| 21 | 21 | assert.equal((await client.request({action:"status"})).installed,false); |
| 22 | 22 | }); |
| 23 | 新增:test("service destinations are validated and forwarded through the same private protocol", async () => { | |
| 24 | 新增: const client = createTailnetClient({ executable: process.execPath, start: (_file,_args,options) => spawn(process.execPath, ["-e", `let text='';process.stdin.on('data',chunk=>{text+=chunk;let end;while((end=text.indexOf('\\n'))>=0){const input=JSON.parse(text.slice(0,end));text=text.slice(end+1);console.log(JSON.stringify(input))}});`], options) }); | |
| 25 | 新增: try { | |
| 26 | 新增: const result = await client.request({action:"open-service",host:"100.88.2.4",port:8080,command:"ignored"}); | |
| 27 | 新增: assert.deepEqual(result,{action:"open-service",host:"100.88.2.4",port:8080}); | |
| 28 | 新增: for (const input of [{host:"100.88.2.4",port:0},{host:"100.88.2.4",port:65536},{host:"100.88.2.4",port:"80"},{host:"100.88.2.4\ncommand",port:80}]) await assert.rejects(client.request({action:"open-service",...input})); | |
| 29 | 新增: assert.equal((await client.request({action:"status"})).action,"status"); | |
| 30 | 新增: } finally {client.close();} | |
| 31 | 新增:}); | |
| @@ -28,13 +28,15 @@ func (s *Server) tailnet(w http.ResponseWriter, r *http.Request) { | ||
| 28 | 28 | return |
| 29 | 29 | } |
| 30 | 30 | switch action { |
| 31 | 删除: case "status", "connect", "login", "disconnect", "logout", "add-key", "remove-key": | |
| 31 | 新增: case "status", "connect", "login", "disconnect", "logout", "add-key", "remove-key", "open-service": | |
| 32 | 32 | default: |
| 33 | 33 | http.NotFound(w, r) |
| 34 | 34 | return |
| 35 | 35 | } |
| 36 | 36 | var input struct { |
| 37 | 删除: Key string `json:"key"` | |
| 37 | 新增: Key string `json:"key"` | |
| 38 | 新增: Host string `json:"host,omitempty"` | |
| 39 | 新增: Port int `json:"port,omitempty"` | |
| 38 | 40 | } |
| 39 | 41 | if r.Method != http.MethodGet && !readJSON(w, r, &input) { |
| 40 | 42 | return |
| @@ -43,6 +45,10 @@ func (s *Server) tailnet(w http.ResponseWriter, r *http.Request) { | ||
| 43 | 45 | http.Error(w, "SSH 公钥过长", 400) |
| 44 | 46 | return |
| 45 | 47 | } |
| 48 | 新增: if action == "open-service" && (len(input.Host) == 0 || len(input.Host) > 253 || input.Port < 1 || input.Port > 65535) { | |
| 49 | 新增: http.Error(w, "请选择私网设备并填写 1–65535 之间的端口", 400) | |
| 50 | 新增: return | |
| 51 | 新增: } | |
| 46 | 52 | s.mu.Lock() |
| 47 | 53 | ready, token := s.ready, s.credentials.Token |
| 48 | 54 | busy := s.jobs.snapshot().Running |
| @@ -53,7 +59,12 @@ func (s *Server) tailnet(w http.ResponseWriter, r *http.Request) { | ||
| 53 | 59 | } |
| 54 | 60 | ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) |
| 55 | 61 | defer cancel() |
| 56 | 删除: body, _ := json.Marshal(map[string]string{"action": action, "key": input.Key}) | |
| 62 | 新增: body, _ := json.Marshal(struct { | |
| 63 | 新增: Action string `json:"action"` | |
| 64 | 新增: Key string `json:"key,omitempty"` | |
| 65 | 新增: Host string `json:"host,omitempty"` | |
| 66 | 新增: Port int `json:"port,omitempty"` | |
| 67 | 新增: }{action, input.Key, input.Host, input.Port}) | |
| 57 | 68 | data, err := s.guestAPI(ctx, token, http.MethodPost, "/tailnet", body) |
| 58 | 69 | if err != nil { |
| 59 | 70 | http.Error(w, "Tailscale 操作未完成。请更新环境组件后重试;原设备身份和 SSH 公钥会保留。", 502) |
| @@ -68,3 +68,36 @@ func TestTailnetGuestContract(t *testing.T) { | ||
| 68 | 68 | t.Fatalf("key error: %d %s", w.Code, w.Body.String()) |
| 69 | 69 | } |
| 70 | 70 | } |
| 71 | 新增: | |
| 72 | 新增:func TestTailnetServicePortContract(t *testing.T) { | |
| 73 | 新增: s := testServer(t) | |
| 74 | 新增: s.ready = true | |
| 75 | 新增: s.credentials.Token = "test-tailnet-token" | |
| 76 | 新增: guest := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 77 | 新增: var input struct { | |
| 78 | 新增: Action string `json:"action"` | |
| 79 | 新增: Host string `json:"host"` | |
| 80 | 新增: Port int `json:"port"` | |
| 81 | 新增: } | |
| 82 | 新增: if err := json.NewDecoder(r.Body).Decode(&input); err != nil { | |
| 83 | 新增: t.Error(err) | |
| 84 | 新增: } | |
| 85 | 新增: if input.Action != "open-service" || input.Host != "100.88.2.4" || input.Port != 8080 { | |
| 86 | 新增: t.Errorf("wrong service input: %+v", input) | |
| 87 | 新增: } | |
| 88 | 新增: _ = json.NewEncoder(w).Encode(map[string]any{"installed": true, "backend": "Running", "forwards": []map[string]any{{"host": input.Host, "port": input.Port, "address": "127.0.0.1:32123"}}}) | |
| 89 | 新增: })) | |
| 90 | 新增: defer guest.Close() | |
| 91 | 新增: s.browserControl = localBrowserClient(t, s.lifetimeContext(), guest) | |
| 92 | 新增: if w := request(s, "POST", "/api/tailscale/open-service", s.origin, `{"host":"100.88.2.4","port":8080}`, true); w.Code != 200 || !strings.Contains(w.Body.String(), "127.0.0.1:32123") { | |
| 93 | 新增: t.Fatalf("service: %d %s", w.Code, w.Body.String()) | |
| 94 | 新增: } | |
| 95 | 新增: for _, body := range []string{`{"host":"100.88.2.4","port":0}`, `{"host":"100.88.2.4","port":65536}`, `{"host":"100.88.2.4","port":"80"}`, `{"port":80}`} { | |
| 96 | 新增: if w := request(s, "POST", "/api/tailscale/open-service", s.origin, body, true); w.Code != 400 { | |
| 97 | 新增: t.Fatalf("bad input accepted: %d %s", w.Code, body) | |
| 98 | 新增: } | |
| 99 | 新增: } | |
| 100 | 新增: if !macOSWorkbenchRoute("/api/tailscale/open-service") || !windowsWorkbenchRoute("/api/tailscale/open-service") { | |
| 101 | 新增: t.Fatal("native hosts must expose the same service route") | |
| 102 | 新增: } | |
| 103 | 新增:} | |
| @@ -2,10 +2,10 @@ package main | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "bufio" |
| 5 | 删除: "context" | |
| 6 | 5 | "crypto/ed25519" |
| 7 | 6 | "crypto/rand" |
| 8 | 7 | "crypto/subtle" |
| 8 | 新增: "encoding/base64" | |
| 9 | 9 | "encoding/hex" |
| 10 | 10 | "encoding/json" |
| 11 | 11 | "encoding/pem" |
| @@ -17,7 +17,6 @@ import ( | ||
| 17 | 17 | "os" |
| 18 | 18 | "path/filepath" |
| 19 | 19 | "strconv" |
| 20 | 删除: "strings" | |
| 21 | 20 | "time" |
| 22 | 21 | |
| 23 | 22 | "golang.org/x/crypto/ssh" |
| @@ -51,8 +50,18 @@ func (n *node) serveDial(listener net.Listener) error { | ||
| 51 | 50 | } |
| 52 | 51 | server := &http.Server{ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 5 * time.Second, MaxHeaderBytes: 4096} |
| 53 | 52 | server.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 54 | 删除: if r.Method != "CONNECT" || r.Header.Get("Origin") != "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+record.Token)) != 1 { | |
| 55 | 删除: http.Error(w, "Forbidden", 403) | |
| 53 | 新增: // The existing SSH transport uses Bearer authentication. Standard proxy | |
| 54 | 新增: // clients use Proxy-Authorization so credentials never reach the peer. | |
| 55 | 新增: proxyAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte("cage:"+record.Token)) | |
| 56 | 新增: standardProxy := subtle.ConstantTimeCompare([]byte(r.Header.Get("Proxy-Authorization")), []byte(proxyAuth)) == 1 | |
| 57 | 新增: controlClient := r.Method == "CONNECT" && r.Header.Get("Origin") == "" && subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+record.Token)) == 1 | |
| 58 | 新增: if !standardProxy && !controlClient { | |
| 59 | 新增: w.Header().Set("Proxy-Authenticate", `Basic realm="Cage Tailscale"`) | |
| 60 | 新增: http.Error(w, "Proxy authentication required", http.StatusProxyAuthRequired) | |
| 61 | 新增: return | |
| 62 | 新增: } | |
| 63 | 新增: if r.Method != "CONNECT" { | |
| 64 | 新增: n.proxyHTTP(w, r) | |
| 56 | 65 | return |
| 57 | 66 | } |
| 58 | 67 | host, port, err := net.SplitHostPort(r.Host) |
| @@ -61,29 +70,7 @@ func (n *node) serveDial(listener net.Listener) error { | ||
| 61 | 70 | http.Error(w, "Invalid target", 400) |
| 62 | 71 | return |
| 63 | 72 | } |
| 64 | 删除: n.mu.Lock() | |
| 65 | 删除: out, err := n.snapshot(r.Context()) | |
| 66 | 删除: ts := n.server | |
| 67 | 删除: allowed := false | |
| 68 | 删除: target := "" | |
| 69 | 删除: if err == nil && ts != nil && out.Backend == "Running" { | |
| 70 | 删除: for _, p := range out.Peers { | |
| 71 | 删除: short, _, _ := strings.Cut(p.Name, ".") | |
| 72 | 删除: if host == p.IP || host == p.Name || host == short { | |
| 73 | 删除: allowed = true | |
| 74 | 删除: target = net.JoinHostPort(p.IP, port) | |
| 75 | 删除: break | |
| 76 | 删除: } | |
| 77 | 删除: } | |
| 78 | 删除: } | |
| 79 | 删除: n.mu.Unlock() | |
| 80 | 删除: if !allowed { | |
| 81 | 删除: http.Error(w, "Unknown tailnet device", 403) | |
| 82 | 删除: return | |
| 83 | 删除: } | |
| 84 | 删除: ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) | |
| 85 | 删除: remote, err := ts.Dial(ctx, "tcp", target) | |
| 86 | 删除: cancel() | |
| 73 | 新增: remote, err := n.dialPeer(r.Context(), host, port) | |
| 87 | 74 | if err != nil { |
| 88 | 75 | http.Error(w, "Tailnet connection failed", 502) |
| 89 | 76 | return |
| @@ -94,33 +81,27 @@ func (n *node) serveDial(listener net.Listener) error { | ||
| 94 | 81 | return |
| 95 | 82 | } |
| 96 | 83 | n.mu.Lock() |
| 97 | 删除: if n.server != ts { | |
| 84 | 新增: peer := remote.(*peerConnection) | |
| 85 | 新增: if n.server != peer.server || !n.connections[peer.Conn] { | |
| 98 | 86 | n.mu.Unlock() |
| 99 | 87 | local.Close() |
| 100 | 88 | remote.Close() |
| 101 | 89 | return |
| 102 | 90 | } |
| 103 | 91 | n.connections[local] = true |
| 104 | 删除: n.connections[remote] = true | |
| 105 | 92 | n.mu.Unlock() |
| 106 | 93 | defer func() { |
| 107 | 94 | local.Close() |
| 108 | 95 | remote.Close() |
| 109 | 96 | n.mu.Lock() |
| 110 | 97 | delete(n.connections, local) |
| 111 | 删除: delete(n.connections, remote) | |
| 112 | 98 | n.mu.Unlock() |
| 113 | 99 | }() |
| 114 | 100 | _, _ = buffer.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n") |
| 115 | 101 | if buffer.Flush() != nil { |
| 116 | 102 | return |
| 117 | 103 | } |
| 118 | 删除: done := make(chan struct{}) | |
| 119 | 删除: go func() { _, _ = io.Copy(remote, buffer); remote.Close(); close(done) }() | |
| 120 | 删除: _, _ = io.Copy(local, remote) | |
| 121 | 删除: local.Close() | |
| 122 | 删除: remote.Close() | |
| 123 | 删除: <-done | |
| 104 | 新增: relayConnection(local, remote, buffer) | |
| 124 | 105 | }) |
| 125 | 106 | go func() { _ = server.Serve(listener) }() |
| 126 | 107 | return nil |
| @@ -24,6 +24,7 @@ import ( | ||
| 24 | 24 | gossh "golang.org/x/crypto/ssh" |
| 25 | 25 | "tailscale.com/client/local" |
| 26 | 26 | "tailscale.com/ipn" |
| 27 | 新增: "tailscale.com/ipn/ipnstate" | |
| 27 | 28 | "tailscale.com/tsnet" |
| 28 | 29 | ) |
| 29 | 30 | |
| @@ -36,25 +37,38 @@ type settings struct { | ||
| 36 | 37 | type request struct { |
| 37 | 38 | Action string `json:"action"` |
| 38 | 39 | Key string `json:"key,omitempty"` |
| 40 | 新增: Host string `json:"host,omitempty"` | |
| 41 | 新增: Port int `json:"port,omitempty"` | |
| 39 | 42 | } |
| 40 | 43 | type peer struct { |
| 41 | 删除: Name string `json:"name"` | |
| 42 | 删除: IP string `json:"ip"` | |
| 43 | 删除: Online bool `json:"online"` | |
| 44 | 新增: ID string `json:"id,omitempty"` | |
| 45 | 新增: Name string `json:"name"` | |
| 46 | 新增: Hostname string `json:"hostname,omitempty"` | |
| 47 | 新增: OS string `json:"os,omitempty"` | |
| 48 | 新增: IP string `json:"ip"` | |
| 49 | 新增: Online bool `json:"online"` | |
| 50 | 新增: LastSeen *time.Time `json:"last_seen,omitempty"` | |
| 44 | 51 | } |
| 45 | 52 | type state struct { |
| 46 | 删除: Installed bool `json:"installed"` | |
| 47 | 删除: Version string `json:"version"` | |
| 48 | 删除: Enabled bool `json:"enabled"` | |
| 49 | 删除: Backend string `json:"backend"` | |
| 50 | 删除: URL string `json:"auth_url,omitempty"` | |
| 51 | 删除: Name string `json:"name,omitempty"` | |
| 52 | 删除: IPs []string `json:"ips"` | |
| 53 | 删除: Peers []peer `json:"peers"` | |
| 54 | 删除: Keys []string `json:"keys"` | |
| 55 | 删除: User string `json:"user"` | |
| 56 | 删除: SSHPort int `json:"ssh_port"` | |
| 57 | 删除: Error string `json:"error,omitempty"` | |
| 53 | 新增: Installed bool `json:"installed"` | |
| 54 | 新增: Version string `json:"version"` | |
| 55 | 新增: Enabled bool `json:"enabled"` | |
| 56 | 新增: Backend string `json:"backend"` | |
| 57 | 新增: URL string `json:"auth_url,omitempty"` | |
| 58 | 新增: Name string `json:"name,omitempty"` | |
| 59 | 新增: Hostname string `json:"hostname,omitempty"` | |
| 60 | 新增: OS string `json:"os,omitempty"` | |
| 61 | 新增: Tailnet string `json:"tailnet,omitempty"` | |
| 62 | 新增: Account string `json:"account,omitempty"` | |
| 63 | 新增: Health []string `json:"health,omitempty"` | |
| 64 | 新增: IPs []string `json:"ips"` | |
| 65 | 新增: Peers []peer `json:"peers"` | |
| 66 | 新增: Keys []string `json:"keys"` | |
| 67 | 新增: User string `json:"user"` | |
| 68 | 新增: SSHPort int `json:"ssh_port"` | |
| 69 | 新增: Error string `json:"error,omitempty"` | |
| 70 | 新增: ProxyURL string `json:"proxy_url,omitempty"` | |
| 71 | 新增: Forwards []forwardState `json:"forwards"` | |
| 58 | 72 | } |
| 59 | 73 | type node struct { |
| 60 | 74 | mu sync.Mutex |
| @@ -65,6 +79,7 @@ type node struct { | ||
| 65 | 79 | ssh *gliderssh.Server |
| 66 | 80 | listener net.Listener |
| 67 | 81 | connections map[net.Conn]bool |
| 82 | 新增: forwards map[string]*tailnetForward | |
| 68 | 83 | } |
| 69 | 84 | |
| 70 | 85 | func dataDir() string { |
| @@ -139,6 +154,7 @@ func (n *node) startServer(s *tsnet.Server) error { | ||
| 139 | 154 | return nil |
| 140 | 155 | } |
| 141 | 156 | func (n *node) stop() { |
| 157 | 新增: n.closeForwards() | |
| 142 | 158 | if n.ssh != nil { |
| 143 | 159 | _ = n.ssh.Close() |
| 144 | 160 | n.ssh = nil |
| @@ -169,12 +185,31 @@ func (n *node) snapshot(ctx context.Context) (state, error) { | ||
| 169 | 185 | if err != nil { |
| 170 | 186 | return out, err |
| 171 | 187 | } |
| 172 | 删除: out.Backend, out.URL = status.BackendState, status.AuthURL | |
| 188 | 新增: applyStatus(&out, status) | |
| 189 | 新增: out.Forwards = n.forwardsSnapshot() | |
| 190 | 新增: if out.Backend == "Running" { | |
| 191 | 新增: out.ProxyURL = n.proxyURL() | |
| 192 | 新增: } | |
| 193 | 新增: if err := n.writeSSHConfig(out.Peers); err != nil { | |
| 194 | 新增: out.Health = append(out.Health, "SSH 自动配置未完成,私网仍可使用:"+err.Error()) | |
| 195 | 新增: } | |
| 196 | 新增: return out, nil | |
| 197 | 新增:} | |
| 198 | 新增: | |
| 199 | 新增:func applyStatus(out *state, status *ipnstate.Status) { | |
| 200 | 新增: out.Backend, out.URL, out.Health = status.BackendState, status.AuthURL, append([]string(nil), status.Health...) | |
| 201 | 新增: if status.CurrentTailnet != nil { | |
| 202 | 新增: out.Tailnet = status.CurrentTailnet.Name | |
| 203 | 新增: } | |
| 173 | 204 | for _, ip := range status.TailscaleIPs { |
| 174 | 205 | out.IPs = append(out.IPs, ip.String()) |
| 175 | 206 | } |
| 176 | 207 | if status.Self != nil { |
| 177 | 208 | out.Name = strings.TrimSuffix(status.Self.DNSName, ".") |
| 209 | 新增: out.Hostname, out.OS = status.Self.HostName, status.Self.OS | |
| 210 | 新增: if user, ok := status.User[status.Self.UserID]; ok { | |
| 211 | 新增: out.Account = user.LoginName | |
| 212 | 新增: } | |
| 178 | 213 | } |
| 179 | 214 | for _, p := range status.Peer { |
| 180 | 215 | for _, ip := range p.TailscaleIPs { |
| @@ -183,16 +218,25 @@ func (n *node) snapshot(ctx context.Context) (state, error) { | ||
| 183 | 218 | if name == "" { |
| 184 | 219 | name = p.HostName |
| 185 | 220 | } |
| 186 | 删除: out.Peers = append(out.Peers, peer{Name: name, IP: ip.String(), Online: p.Online}) | |
| 221 | 新增: entry := peer{ID: string(p.ID), Name: name, Hostname: p.HostName, OS: p.OS, IP: ip.String(), Online: p.Online} | |
| 222 | 新增: if !p.LastSeen.IsZero() { | |
| 223 | 新增: seen := p.LastSeen | |
| 224 | 新增: entry.LastSeen = &seen | |
| 225 | 新增: } | |
| 226 | 新增: out.Peers = append(out.Peers, entry) | |
| 187 | 227 | break |
| 188 | 228 | } |
| 189 | 229 | } |
| 190 | 230 | } |
| 191 | 删除: slices.SortFunc(out.Peers, func(a, b peer) int { return strings.Compare(a.Name, b.Name) }) | |
| 192 | 删除: if err := n.writeSSHConfig(out.Peers); err != nil { | |
| 193 | 删除: return out, err | |
| 194 | 删除: } | |
| 195 | 删除: return out, nil | |
| 231 | 新增: slices.SortFunc(out.Peers, func(a, b peer) int { | |
| 232 | 新增: if a.Online != b.Online { | |
| 233 | 新增: if a.Online { | |
| 234 | 新增: return -1 | |
| 235 | 新增: } | |
| 236 | 新增: return 1 | |
| 237 | 新增: } | |
| 238 | 新增: return strings.Compare(a.Name, b.Name) | |
| 239 | 新增: }) | |
| 196 | 240 | } |
| 197 | 241 | func currentUser() string { |
| 198 | 242 | u, err := user.Current() |
| @@ -206,6 +250,10 @@ func (n *node) run(ctx context.Context, r request) (state, error) { | ||
| 206 | 250 | defer n.mu.Unlock() |
| 207 | 251 | switch r.Action { |
| 208 | 252 | case "status": |
| 253 | 新增: case "open-service": | |
| 254 | 新增: if _, err := n.openForward(ctx, r.Host, r.Port); err != nil { | |
| 255 | 新增: return state{}, err | |
| 256 | 新增: } | |
| 209 | 257 | case "connect", "login": |
| 210 | 258 | if err := n.start(); err != nil { |
| 211 | 259 | return state{}, err |
| @@ -215,7 +263,11 @@ func (n *node) run(ctx context.Context, r request) (state, error) { | ||
| 215 | 263 | n.stop() |
| 216 | 264 | return state{}, err |
| 217 | 265 | } |
| 218 | 删除: if r.Action == "login" { | |
| 266 | 新增: status, err := n.client.Status(ctx) | |
| 267 | 新增: if err != nil { | |
| 268 | 新增: return state{}, err | |
| 269 | 新增: } | |
| 270 | 新增: if r.Action == "login" || !status.HaveNodeKey || status.BackendState == "NeedsLogin" { | |
| 219 | 271 | if err := n.client.StartLoginInteractive(ctx); err != nil { |
| 220 | 272 | return state{}, err |
| 221 | 273 | } |
| @@ -309,7 +309,7 @@ func TestInteractiveAuthorizationFlow(t *testing.T) { | ||
| 309 | 309 | defer n.stop() |
| 310 | 310 | ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) |
| 311 | 311 | defer cancel() |
| 312 | 删除: if _, err = n.run(ctx, request{Action: "login"}); err != nil { | |
| 312 | 新增: if _, err = n.run(ctx, request{Action: "connect"}); err != nil { | |
| 313 | 313 | t.Fatal(err) |
| 314 | 314 | } |
| 315 | 315 | var value state |
| @@ -333,6 +333,18 @@ func TestInteractiveAuthorizationFlow(t *testing.T) { | ||
| 333 | 333 | if err != nil || value.Backend != "Running" { |
| 334 | 334 | t.Fatalf("login not running: %+v %v", value, err) |
| 335 | 335 | } |
| 336 | 新增: // A broken optional SSH configuration must not hide a healthy private network. | |
| 337 | 新增: sshConfig := filepath.Join(os.Getenv("HOME"), ".ssh", "config") | |
| 338 | 新增: if err := os.Remove(sshConfig); err != nil { | |
| 339 | 新增: t.Fatal(err) | |
| 340 | 新增: } | |
| 341 | 新增: if err := os.Mkdir(sshConfig, 0700); err != nil { | |
| 342 | 新增: t.Fatal(err) | |
| 343 | 新增: } | |
| 344 | 新增: value, err = n.run(ctx, request{Action: "status"}) | |
| 345 | 新增: if err != nil || value.Backend != "Running" || !strings.Contains(strings.Join(value.Health, "\n"), "SSH 自动配置未完成") { | |
| 346 | 新增: t.Fatalf("SSH configuration failure hid network status: %+v %v", value, err) | |
| 347 | 新增: } | |
| 336 | 348 | } |
| 337 | 349 | |
| 338 | 350 | func waitDERP(t *testing.T, ctx context.Context, s *tsnet.Server) { |
| @@ -0,0 +1,160 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "io" | |
| 7 | 新增: "net" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "strconv" | |
| 10 | 新增: "strings" | |
| 11 | 新增: "time" | |
| 12 | 新增: | |
| 13 | 新增: "tailscale.com/tsnet" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:// dialPeer is deliberately limited to visible tailnet peers. In particular the | |
| 17 | 新增:// proxy never falls back to a guest/host socket for public, loopback or LAN IPs. | |
| 18 | 新增:func (n *node) dialPeer(ctx context.Context, host, port string) (net.Conn, error) { | |
| 19 | 新增: return n.dialPeerOn(ctx, host, port, nil) | |
| 20 | 新增:} | |
| 21 | 新增: | |
| 22 | 新增:func (n *node) dialPeerOn(ctx context.Context, host, port string, expected *tsnet.Server) (net.Conn, error) { | |
| 23 | 新增: number, err := strconv.Atoi(port) | |
| 24 | 新增: if err != nil || number < 1 || number > 65535 { | |
| 25 | 新增: return nil, errors.New("invalid tailnet port") | |
| 26 | 新增: } | |
| 27 | 新增: host = strings.TrimSuffix(strings.ToLower(host), ".") | |
| 28 | 新增: n.mu.Lock() | |
| 29 | 新增: out, err := n.snapshot(ctx) | |
| 30 | 新增: ts := n.server | |
| 31 | 新增: target := "" | |
| 32 | 新增: if err == nil && ts != nil && (expected == nil || expected == ts) && out.Backend == "Running" { | |
| 33 | 新增: for _, p := range out.Peers { | |
| 34 | 新增: name := strings.ToLower(p.Name) | |
| 35 | 新增: short, _, _ := strings.Cut(name, ".") | |
| 36 | 新增: if host == p.IP || host == name || host == short { | |
| 37 | 新增: target = net.JoinHostPort(p.IP, port) | |
| 38 | 新增: break | |
| 39 | 新增: } | |
| 40 | 新增: } | |
| 41 | 新增: } | |
| 42 | 新增: n.mu.Unlock() | |
| 43 | 新增: if target == "" { | |
| 44 | 新增: return nil, errors.New("unknown tailnet device or disconnected") | |
| 45 | 新增: } | |
| 46 | 新增: ctx, cancel := context.WithTimeout(ctx, 15*time.Second) | |
| 47 | 新增: defer cancel() | |
| 48 | 新增: remote, err := ts.Dial(ctx, "tcp", target) | |
| 49 | 新增: if err != nil { | |
| 50 | 新增: return nil, err | |
| 51 | 新增: } | |
| 52 | 新增: n.mu.Lock() | |
| 53 | 新增: defer n.mu.Unlock() | |
| 54 | 新增: if n.server != ts { | |
| 55 | 新增: remote.Close() | |
| 56 | 新增: return nil, errors.New("tailnet disconnected") | |
| 57 | 新增: } | |
| 58 | 新增: n.connections[remote] = true | |
| 59 | 新增: return &peerConnection{Conn: remote, node: n, server: ts}, nil | |
| 60 | 新增:} | |
| 61 | 新增: | |
| 62 | 新增:type peerConnection struct { | |
| 63 | 新增: net.Conn | |
| 64 | 新增: node *node | |
| 65 | 新增: server *tsnet.Server | |
| 66 | 新增:} | |
| 67 | 新增: | |
| 68 | 新增:func (c *peerConnection) Close() error { | |
| 69 | 新增: err := c.Conn.Close() | |
| 70 | 新增: c.node.mu.Lock() | |
| 71 | 新增: delete(c.node.connections, c.Conn) | |
| 72 | 新增: c.node.mu.Unlock() | |
| 73 | 新增: return err | |
| 74 | 新增:} | |
| 75 | 新增: | |
| 76 | 新增:func (c *peerConnection) CloseWrite() error { | |
| 77 | 新增: if tcp, ok := c.Conn.(interface{ CloseWrite() error }); ok { | |
| 78 | 新增: return tcp.CloseWrite() | |
| 79 | 新增: } | |
| 80 | 新增: return c.Close() | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:// A FIN in one direction must not discard bytes still flowing back. Both | |
| 84 | 新增:// sockets stay tracked until both halves finish or the node revokes them. | |
| 85 | 新增:func relayConnection(local net.Conn, remote net.Conn, input io.Reader) { | |
| 86 | 新增: copyHalf := func(dst net.Conn, src io.Reader) { | |
| 87 | 新增: if _, err := io.Copy(dst, src); err != nil { | |
| 88 | 新增: _ = dst.Close() | |
| 89 | 新增: return | |
| 90 | 新增: } | |
| 91 | 新增: if tcp, ok := dst.(interface{ CloseWrite() error }); ok { | |
| 92 | 新增: _ = tcp.CloseWrite() | |
| 93 | 新增: } else { | |
| 94 | 新增: _ = dst.Close() | |
| 95 | 新增: } | |
| 96 | 新增: } | |
| 97 | 新增: done := make(chan struct{}) | |
| 98 | 新增: go func() { copyHalf(remote, input); close(done) }() | |
| 99 | 新增: copyHalf(local, remote) | |
| 100 | 新增: <-done | |
| 101 | 新增:} | |
| 102 | 新增: | |
| 103 | 新增:func stripProxyHeaders(h http.Header) { | |
| 104 | 新增: for _, name := range strings.Split(h.Get("Connection"), ",") { | |
| 105 | 新增: h.Del(strings.TrimSpace(name)) | |
| 106 | 新增: } | |
| 107 | 新增: for _, name := range []string{"Connection", "Proxy-Connection", "Proxy-Authorization", "Proxy-Authenticate", "Keep-Alive", "TE", "Trailer", "Transfer-Encoding", "Upgrade"} { | |
| 108 | 新增: h.Del(name) | |
| 109 | 新增: } | |
| 110 | 新增:} | |
| 111 | 新增: | |
| 112 | 新增:func (n *node) proxyHTTP(w http.ResponseWriter, r *http.Request) { | |
| 113 | 新增: if !r.URL.IsAbs() || r.URL.Scheme != "http" || r.URL.User != nil || r.URL.Host != r.Host || r.URL.Fragment != "" { | |
| 114 | 新增: http.Error(w, "Expected an absolute HTTP proxy URL", http.StatusBadRequest) | |
| 115 | 新增: return | |
| 116 | 新增: } | |
| 117 | 新增: port := r.URL.Port() | |
| 118 | 新增: if port == "" { | |
| 119 | 新增: port = "80" | |
| 120 | 新增: } | |
| 121 | 新增: remote, err := n.dialPeer(r.Context(), r.URL.Hostname(), port) | |
| 122 | 新增: if err != nil { | |
| 123 | 新增: http.Error(w, "Tailnet device unavailable", http.StatusBadGateway) | |
| 124 | 新增: return | |
| 125 | 新增: } | |
| 126 | 新增: defer remote.Close() | |
| 127 | 新增: // One connection per request avoids keeping connections across a logout or | |
| 128 | 新增: // a device identity change. The node tracks it so disconnect closes streams. | |
| 129 | 新增: transport := &http.Transport{Proxy: nil, DisableKeepAlives: true, ResponseHeaderTimeout: 15 * time.Second, | |
| 130 | 新增: DialContext: func(context.Context, string, string) (net.Conn, error) { return remote, nil }, | |
| 131 | 新增: } | |
| 132 | 新增: defer transport.CloseIdleConnections() | |
| 133 | 新增: request := r.Clone(r.Context()) | |
| 134 | 新增: request.RequestURI = "" | |
| 135 | 新增: request.Header = r.Header.Clone() | |
| 136 | 新增: stripProxyHeaders(request.Header) | |
| 137 | 新增: response, err := transport.RoundTrip(request) | |
| 138 | 新增: if err != nil { | |
| 139 | 新增: http.Error(w, "Tailnet service did not respond", http.StatusBadGateway) | |
| 140 | 新增: return | |
| 141 | 新增: } | |
| 142 | 新增: defer response.Body.Close() | |
| 143 | 新增: stripProxyHeaders(response.Header) | |
| 144 | 新增: for key, values := range response.Header { | |
| 145 | 新增: w.Header()[key] = values | |
| 146 | 新增: } | |
| 147 | 新增: w.WriteHeader(response.StatusCode) | |
| 148 | 新增: _, _ = io.Copy(proxyResponseWriter{w}, response.Body) | |
| 149 | 新增:} | |
| 150 | 新增: | |
| 151 | 新增:// Flush incremental responses so tailnet web UIs can use SSE and streaming. | |
| 152 | 新增:type proxyResponseWriter struct{ http.ResponseWriter } | |
| 153 | 新增: | |
| 154 | 新增:func (w proxyResponseWriter) Write(p []byte) (int, error) { | |
| 155 | 新增: n, err := w.ResponseWriter.Write(p) | |
| 156 | 新增: if n > 0 { | |
| 157 | 新增: _ = http.NewResponseController(w.ResponseWriter).Flush() | |
| 158 | 新增: } | |
| 159 | 新增: return n, err | |
| 160 | 新增:} | |
| @@ -0,0 +1,144 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "net" | |
| 8 | 新增: "net/url" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "slices" | |
| 12 | 新增: "strconv" | |
| 13 | 新增: "strings" | |
| 14 | 新增: | |
| 15 | 新增: "tailscale.com/tsnet" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:type forwardState struct { | |
| 19 | 新增: Host string `json:"host"` | |
| 20 | 新增: Port int `json:"port"` | |
| 21 | 新增: Address string `json:"address"` | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:type tailnetForward struct { | |
| 25 | 新增: forwardState | |
| 26 | 新增: server *tsnet.Server | |
| 27 | 新增: listener net.Listener | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:// openForward, closeForwards and forwardsSnapshot run under n.mu, like snapshot. | |
| 31 | 新增:// All application data stays inside the guest; only a loopback port is opened. | |
| 32 | 新增:func (n *node) openForward(ctx context.Context, host string, port int) (string, error) { | |
| 33 | 新增: if port < 1 || port > 65535 { | |
| 34 | 新增: return "", errors.New("服务端口必须介于 1 和 65535 之间") | |
| 35 | 新增: } | |
| 36 | 新增: out, err := n.snapshot(ctx) | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: return "", err | |
| 39 | 新增: } | |
| 40 | 新增: if n.server == nil || out.Backend != "Running" { | |
| 41 | 新增: return "", errors.New("请先连接 Tailscale") | |
| 42 | 新增: } | |
| 43 | 新增: host = strings.TrimSuffix(strings.ToLower(host), ".") | |
| 44 | 新增: ip := "" | |
| 45 | 新增: for _, peer := range out.Peers { | |
| 46 | 新增: name := strings.ToLower(peer.Name) | |
| 47 | 新增: short, _, _ := strings.Cut(name, ".") | |
| 48 | 新增: if host == peer.IP || host == name || host == short { | |
| 49 | 新增: ip = peer.IP | |
| 50 | 新增: break | |
| 51 | 新增: } | |
| 52 | 新增: } | |
| 53 | 新增: if ip == "" { | |
| 54 | 新增: return "", errors.New("设备未出现在当前 Tailscale 网络中") | |
| 55 | 新增: } | |
| 56 | 新增: key := net.JoinHostPort(ip, strconv.Itoa(port)) | |
| 57 | 新增: if previous := n.forwards[key]; previous != nil && previous.server == n.server { | |
| 58 | 新增: return previous.Address, nil | |
| 59 | 新增: } | |
| 60 | 新增: if len(n.forwards) >= 32 { | |
| 61 | 新增: return "", errors.New("最多同时连接 32 个私网服务,请断开 Tailscale 后重试") | |
| 62 | 新增: } | |
| 63 | 新增: listener, err := net.Listen("tcp4", "127.0.0.1:0") | |
| 64 | 新增: if err != nil { | |
| 65 | 新增: return "", err | |
| 66 | 新增: } | |
| 67 | 新增: forward := &tailnetForward{forwardState: forwardState{Host: ip, Port: port, Address: listener.Addr().String()}, server: n.server, listener: listener} | |
| 68 | 新增: if n.forwards == nil { | |
| 69 | 新增: n.forwards = make(map[string]*tailnetForward) | |
| 70 | 新增: } | |
| 71 | 新增: n.forwards[key] = forward | |
| 72 | 新增: go n.acceptForward(key, forward) | |
| 73 | 新增: return forward.Address, nil | |
| 74 | 新增:} | |
| 75 | 新增: | |
| 76 | 新增:func (n *node) closeForwards() { | |
| 77 | 新增: for _, forward := range n.forwards { | |
| 78 | 新增: _ = forward.listener.Close() | |
| 79 | 新增: } | |
| 80 | 新增: clear(n.forwards) | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:func (n *node) forwardsSnapshot() []forwardState { | |
| 84 | 新增: result := make([]forwardState, 0, len(n.forwards)) | |
| 85 | 新增: for _, forward := range n.forwards { | |
| 86 | 新增: if forward.server == n.server { | |
| 87 | 新增: result = append(result, forward.forwardState) | |
| 88 | 新增: } | |
| 89 | 新增: } | |
| 90 | 新增: slices.SortFunc(result, func(a, b forwardState) int { | |
| 91 | 新增: if a.Host != b.Host { | |
| 92 | 新增: return strings.Compare(a.Host, b.Host) | |
| 93 | 新增: } | |
| 94 | 新增: return a.Port - b.Port | |
| 95 | 新增: }) | |
| 96 | 新增: return result | |
| 97 | 新增:} | |
| 98 | 新增: | |
| 99 | 新增:func (n *node) proxyURL() string { | |
| 100 | 新增: if n.server == nil { | |
| 101 | 新增: return "" | |
| 102 | 新增: } | |
| 103 | 新增: b, err := os.ReadFile(filepath.Join(n.dir, "control.json")) | |
| 104 | 新增: if err != nil { | |
| 105 | 新增: return "" | |
| 106 | 新增: } | |
| 107 | 新增: var record dialRecord | |
| 108 | 新增: if json.Unmarshal(b, &record) != nil || record.Token == "" { | |
| 109 | 新增: return "" | |
| 110 | 新增: } | |
| 111 | 新增: host, _, err := net.SplitHostPort(record.Address) | |
| 112 | 新增: if err != nil || host != "127.0.0.1" { | |
| 113 | 新增: return "" | |
| 114 | 新增: } | |
| 115 | 新增: return (&url.URL{Scheme: "http", Host: record.Address, User: url.UserPassword("cage", record.Token)}).String() | |
| 116 | 新增:} | |
| 117 | 新增: | |
| 118 | 新增:func (n *node) acceptForward(key string, forward *tailnetForward) { | |
| 119 | 新增: for { | |
| 120 | 新增: local, err := forward.listener.Accept() | |
| 121 | 新增: if err != nil { | |
| 122 | 新增: return | |
| 123 | 新增: } | |
| 124 | 新增: go n.forwardConnection(key, forward, local) | |
| 125 | 新增: } | |
| 126 | 新增:} | |
| 127 | 新增: | |
| 128 | 新增:func (n *node) forwardConnection(key string, forward *tailnetForward, local net.Conn) { | |
| 129 | 新增: n.mu.Lock() | |
| 130 | 新增: if n.server != forward.server || n.forwards[key] != forward { | |
| 131 | 新增: n.mu.Unlock() | |
| 132 | 新增: local.Close() | |
| 133 | 新增: return | |
| 134 | 新增: } | |
| 135 | 新增: n.connections[local] = true | |
| 136 | 新增: n.mu.Unlock() | |
| 137 | 新增: defer func() { local.Close(); n.mu.Lock(); delete(n.connections, local); n.mu.Unlock() }() | |
| 138 | 新增: remote, err := n.dialPeerOn(context.Background(), forward.Host, strconv.Itoa(forward.Port), forward.server) | |
| 139 | 新增: if err != nil { | |
| 140 | 新增: return | |
| 141 | 新增: } | |
| 142 | 新增: defer remote.Close() | |
| 143 | 新增: relayConnection(local, remote, local) | |
| 144 | 新增:} | |
| @@ -0,0 +1,297 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bufio" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/tls" | |
| 7 | 新增: "encoding/base64" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "fmt" | |
| 10 | 新增: "io" | |
| 11 | 新增: "net" | |
| 12 | 新增: "net/http" | |
| 13 | 新增: "net/http/httptest" | |
| 14 | 新增: "net/url" | |
| 15 | 新增: "os" | |
| 16 | 新增: "path/filepath" | |
| 17 | 新增: "strings" | |
| 18 | 新增: "tailscale.com/envknob" | |
| 19 | 新增: "tailscale.com/net/netns" | |
| 20 | 新增: "tailscale.com/tailcfg" | |
| 21 | 新增: "tailscale.com/tsnet" | |
| 22 | 新增: "tailscale.com/tstest/integration" | |
| 23 | 新增: "tailscale.com/tstest/integration/testcontrol" | |
| 24 | 新增: "tailscale.com/types/logger" | |
| 25 | 新增: "testing" | |
| 26 | 新增: "time" | |
| 27 | 新增:) | |
| 28 | 新增: | |
| 29 | 新增:func TestHTTPProxyUsesTailnetAndRevokesConnections(t *testing.T) { | |
| 30 | 新增: t.Setenv("HOME", t.TempDir()) | |
| 31 | 新增: t.Setenv("USERPROFILE", os.Getenv("HOME")) | |
| 32 | 新增: t.Setenv("TS_NO_LOGS_NO_SUPPORT", "true") | |
| 33 | 新增: envknob.SetenvForTest(t, "TS_DEBUG_ALWAYS_USE_DERP", "true") | |
| 34 | 新增: netns.SetEnabled(false) | |
| 35 | 新增: defer netns.SetEnabled(true) | |
| 36 | 新增: control := &testcontrol.Server{DERPMap: integration.RunDERPAndSTUN(t, logger.Discard, "127.0.0.1"), MagicDNSDomain: "cage-test.ts.net", DNSConfig: &tailcfg.DNSConfig{Proxied: true}, Logf: logger.Discard} | |
| 37 | 新增: server := httptest.NewUnstartedServer(control) | |
| 38 | 新增: control.HTTPTestServer = server | |
| 39 | 新增: server.Start() | |
| 40 | 新增: defer server.Close() | |
| 41 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) | |
| 42 | 新增: defer cancel() | |
| 43 | 新增: n, err := newNode(t.TempDir()) | |
| 44 | 新增: if err != nil { | |
| 45 | 新增: t.Fatal(err) | |
| 46 | 新增: } | |
| 47 | 新增: if err = n.startServer(&tsnet.Server{Dir: n.dir, Hostname: "cage-proxy", ControlURL: server.URL, UserLogf: logger.Discard}); err != nil { | |
| 48 | 新增: t.Fatal(err) | |
| 49 | 新增: } | |
| 50 | 新增: defer func() { n.mu.Lock(); n.stop(); n.mu.Unlock() }() | |
| 51 | 新增: n.config.Enabled = true | |
| 52 | 新增: if _, err = n.server.Up(ctx); err != nil { | |
| 53 | 新增: t.Fatal(err) | |
| 54 | 新增: } | |
| 55 | 新增: remote := &tsnet.Server{Dir: t.TempDir(), Hostname: "private-web", ControlURL: server.URL, UserLogf: logger.Discard} | |
| 56 | 新增: defer remote.Close() | |
| 57 | 新增: peer, err := remote.Up(ctx) | |
| 58 | 新增: if err != nil { | |
| 59 | 新增: t.Fatal(err) | |
| 60 | 新增: } | |
| 61 | 新增: waitDERP(t, ctx, n.server) | |
| 62 | 新增: waitDERP(t, ctx, remote) | |
| 63 | 新增: for { | |
| 64 | 新增: snapshot, err := n.run(ctx, request{Action: "status"}) | |
| 65 | 新增: if err == nil && len(snapshot.Peers) > 0 { | |
| 66 | 新增: break | |
| 67 | 新增: } | |
| 68 | 新增: select { | |
| 69 | 新增: case <-ctx.Done(): | |
| 70 | 新增: t.Fatal(ctx.Err()) | |
| 71 | 新增: case <-time.After(20 * time.Millisecond): | |
| 72 | 新增: } | |
| 73 | 新增: } | |
| 74 | 新增: listener, err := remote.Listen("tcp", ":8080") | |
| 75 | 新增: if err != nil { | |
| 76 | 新增: t.Fatal(err) | |
| 77 | 新增: } | |
| 78 | 新增: web := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 79 | 新增: if r.Header.Get("Proxy-Authorization") != "" || r.Header.Get("X-Remove") != "" { | |
| 80 | 新增: t.Error("proxy headers reached private service") | |
| 81 | 新增: } | |
| 82 | 新增: if r.URL.Path == "/stream" { | |
| 83 | 新增: w.Header().Set("Content-Type", "text/event-stream") | |
| 84 | 新增: fmt.Fprint(w, "data: live\n\n") | |
| 85 | 新增: w.(http.Flusher).Flush() | |
| 86 | 新增: <-r.Context().Done() | |
| 87 | 新增: return | |
| 88 | 新增: } | |
| 89 | 新增: body, _ := io.ReadAll(r.Body) | |
| 90 | 新增: w.Header().Set("X-Tailnet-Service", "private-web") | |
| 91 | 新增: w.WriteHeader(http.StatusCreated) | |
| 92 | 新增: fmt.Fprintf(w, "%s %s %s", r.Method, r.URL.RequestURI(), body) | |
| 93 | 新增: })} | |
| 94 | 新增: go web.Serve(listener) | |
| 95 | 新增: defer web.Close() | |
| 96 | 新增: // Reuse a short-lived test certificate while carrying real TLS over tsnet. | |
| 97 | 新增: certificateServer := httptest.NewTLSServer(web.Handler) | |
| 98 | 新增: defer certificateServer.Close() | |
| 99 | 新增: tlsListener, err := remote.Listen("tcp", ":8443") | |
| 100 | 新增: if err != nil { | |
| 101 | 新增: t.Fatal(err) | |
| 102 | 新增: } | |
| 103 | 新增: secureWeb := &http.Server{Handler: web.Handler} | |
| 104 | 新增: go secureWeb.Serve(tls.NewListener(tlsListener, certificateServer.TLS)) | |
| 105 | 新增: defer secureWeb.Close() | |
| 106 | 新增: proxyListener, err := net.Listen("tcp4", "127.0.0.1:0") | |
| 107 | 新增: if err != nil { | |
| 108 | 新增: t.Fatal(err) | |
| 109 | 新增: } | |
| 110 | 新增: defer proxyListener.Close() | |
| 111 | 新增: if err = n.serveDial(proxyListener); err != nil { | |
| 112 | 新增: t.Fatal(err) | |
| 113 | 新增: } | |
| 114 | 新增: var record dialRecord | |
| 115 | 新增: b, _ := os.ReadFile(filepath.Join(n.dir, "control.json")) | |
| 116 | 新增: if err = json.Unmarshal(b, &record); err != nil { | |
| 117 | 新增: t.Fatal(err) | |
| 118 | 新增: } | |
| 119 | 新增: proxyURL := &url.URL{Scheme: "http", Host: record.Address, User: url.UserPassword("cage", record.Token)} | |
| 120 | 新增: transport := &http.Transport{Proxy: http.ProxyURL(proxyURL), DisableKeepAlives: true, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} | |
| 121 | 新增: defer transport.CloseIdleConnections() | |
| 122 | 新增: client := &http.Client{Transport: transport, Timeout: 10 * time.Second} | |
| 123 | 新增: for _, host := range []string{peer.TailscaleIPs[0].String(), "private-web.cage-test.ts.net", "private-web"} { | |
| 124 | 新增: r, _ := http.NewRequestWithContext(ctx, "POST", "http://"+host+":8080/hello?q=world", strings.NewReader("payload")) | |
| 125 | 新增: r.Header.Set("Connection", "X-Remove") | |
| 126 | 新增: r.Header.Set("X-Remove", "secret") | |
| 127 | 新增: response, err := client.Do(r) | |
| 128 | 新增: if err != nil { | |
| 129 | 新增: t.Fatal(err) | |
| 130 | 新增: } | |
| 131 | 新增: body, _ := io.ReadAll(response.Body) | |
| 132 | 新增: response.Body.Close() | |
| 133 | 新增: if response.StatusCode != http.StatusCreated || string(body) != "POST /hello?q=world payload" || response.Header.Get("X-Tailnet-Service") != "private-web" { | |
| 134 | 新增: t.Fatalf("proxy response: %d %q", response.StatusCode, body) | |
| 135 | 新增: } | |
| 136 | 新增: } | |
| 137 | 新增: secureResponse, err := client.Get("https://private-web:8443/encrypted") | |
| 138 | 新增: if err != nil { | |
| 139 | 新增: t.Fatal(err) | |
| 140 | 新增: } | |
| 141 | 新增: secureBody, _ := io.ReadAll(secureResponse.Body) | |
| 142 | 新增: secureResponse.Body.Close() | |
| 143 | 新增: if secureResponse.TLS == nil || string(secureBody) != "GET /encrypted " { | |
| 144 | 新增: t.Fatalf("HTTPS did not traverse tailnet: %q", secureBody) | |
| 145 | 新增: } | |
| 146 | 新增: stream, err := client.Get("http://private-web:8080/stream") | |
| 147 | 新增: if err != nil { | |
| 148 | 新增: t.Fatal(err) | |
| 149 | 新增: } | |
| 150 | 新增: line, err := bufio.NewReader(stream.Body).ReadString('\n') | |
| 151 | 新增: stream.Body.Close() | |
| 152 | 新增: if err != nil || line != "data: live\n" { | |
| 153 | 新增: t.Fatalf("stream buffered: %q %v", line, err) | |
| 154 | 新增: } | |
| 155 | 新增: for _, target := range []string{"http://127.0.0.1:8080/", "http://1.1.1.1/", "http://192.168.1.1/", "http://unknown.cage-test.ts.net/"} { | |
| 156 | 新增: response, err := client.Get(target) | |
| 157 | 新增: if err != nil { | |
| 158 | 新增: t.Fatal(err) | |
| 159 | 新增: } | |
| 160 | 新增: response.Body.Close() | |
| 161 | 新增: if response.StatusCode != http.StatusBadGateway { | |
| 162 | 新增: t.Fatalf("non-peer %s accepted: %d", target, response.StatusCode) | |
| 163 | 新增: } | |
| 164 | 新增: } | |
| 165 | 新增: unauthTransport := &http.Transport{Proxy: http.ProxyURL(&url.URL{Scheme: "http", Host: record.Address})} | |
| 166 | 新增: defer unauthTransport.CloseIdleConnections() | |
| 167 | 新增: unauth := &http.Client{Transport: unauthTransport, Timeout: 5 * time.Second} | |
| 168 | 新增: response, err := unauth.Get("http://private-web:8080/") | |
| 169 | 新增: if err != nil { | |
| 170 | 新增: t.Fatal(err) | |
| 171 | 新增: } | |
| 172 | 新增: response.Body.Close() | |
| 173 | 新增: if response.StatusCode != http.StatusProxyAuthRequired { | |
| 174 | 新增: t.Fatalf("missing auth accepted: %d", response.StatusCode) | |
| 175 | 新增: } | |
| 176 | 新增: open := func(host string, port int) (string, error) { | |
| 177 | 新增: n.mu.Lock() | |
| 178 | 新增: defer n.mu.Unlock() | |
| 179 | 新增: return n.openForward(ctx, host, port) | |
| 180 | 新增: } | |
| 181 | 新增: for _, invalid := range []struct { | |
| 182 | 新增: host string | |
| 183 | 新增: port int | |
| 184 | 新增: }{{"private-web", 0}, {"private-web", 65536}, {"127.0.0.1", 8080}, {"1.1.1.1", 443}, {"unknown", 8080}} { | |
| 185 | 新增: if address, err := open(invalid.host, invalid.port); err == nil { | |
| 186 | 新增: t.Fatalf("invalid forward accepted: %+v %s", invalid, address) | |
| 187 | 新增: } | |
| 188 | 新增: } | |
| 189 | 新增: address, err := open("private-web", 8080) | |
| 190 | 新增: if err != nil { | |
| 191 | 新增: t.Fatal(err) | |
| 192 | 新增: } | |
| 193 | 新增: if again, err := open(peer.TailscaleIPs[0].String(), 8080); err != nil || again != address { | |
| 194 | 新增: t.Fatalf("duplicate mapping not reused: %s %s %v", address, again, err) | |
| 195 | 新增: } | |
| 196 | 新增: direct := &http.Client{Transport: &http.Transport{Proxy: nil}, Timeout: 5 * time.Second} | |
| 197 | 新增: localResponse, err := direct.Get("http://" + address + "/local-service") | |
| 198 | 新增: if err != nil { | |
| 199 | 新增: t.Fatal(err) | |
| 200 | 新增: } | |
| 201 | 新增: localBody, _ := io.ReadAll(localResponse.Body) | |
| 202 | 新增: localResponse.Body.Close() | |
| 203 | 新增: if string(localBody) != "GET /local-service " { | |
| 204 | 新增: t.Fatalf("mapped HTTP: %q", localBody) | |
| 205 | 新增: } | |
| 206 | 新增: echoListener, err := remote.Listen("tcp", ":9001") | |
| 207 | 新增: if err != nil { | |
| 208 | 新增: t.Fatal(err) | |
| 209 | 新增: } | |
| 210 | 新增: defer echoListener.Close() | |
| 211 | 新增: go func() { | |
| 212 | 新增: for { | |
| 213 | 新增: c, e := echoListener.Accept() | |
| 214 | 新增: if e != nil { | |
| 215 | 新增: return | |
| 216 | 新增: } | |
| 217 | 新增: go func() { defer c.Close(); _, _ = io.Copy(c, c) }() | |
| 218 | 新增: } | |
| 219 | 新增: }() | |
| 220 | 新增: echoAddress, err := open("private-web", 9001) | |
| 221 | 新增: if err != nil { | |
| 222 | 新增: t.Fatal(err) | |
| 223 | 新增: } | |
| 224 | 新增: echo, err := net.DialTimeout("tcp", echoAddress, time.Second) | |
| 225 | 新增: if err != nil { | |
| 226 | 新增: t.Fatal(err) | |
| 227 | 新增: } | |
| 228 | 新增: defer echo.Close() | |
| 229 | 新增: echo.SetDeadline(time.Now().Add(10 * time.Second)) | |
| 230 | 新增: _, _ = echo.Write([]byte("arbitrary TCP payload")) | |
| 231 | 新增: echoPayload := make([]byte, len("arbitrary TCP payload")) | |
| 232 | 新增: if _, err = io.ReadFull(echo, echoPayload); err != nil || string(echoPayload) != "arbitrary TCP payload" { | |
| 233 | 新增: t.Fatalf("mapped TCP: %q %v", echoPayload, err) | |
| 234 | 新增: } | |
| 235 | 新增: half, err := net.DialTimeout("tcp", echoAddress, time.Second) | |
| 236 | 新增: if err != nil { | |
| 237 | 新增: t.Fatal(err) | |
| 238 | 新增: } | |
| 239 | 新增: half.SetDeadline(time.Now().Add(5 * time.Second)) | |
| 240 | 新增: _, _ = half.Write([]byte("reply after FIN")) | |
| 241 | 新增: _ = half.(*net.TCPConn).CloseWrite() | |
| 242 | 新增: halfReply, err := io.ReadAll(half) | |
| 243 | 新增: half.Close() | |
| 244 | 新增: if err != nil || string(halfReply) != "reply after FIN" { | |
| 245 | 新增: t.Fatalf("half-closed TCP reply: %q %v", halfReply, err) | |
| 246 | 新增: } | |
| 247 | 新增: conn, err := net.DialTimeout("tcp", record.Address, time.Second) | |
| 248 | 新增: if err != nil { | |
| 249 | 新增: t.Fatal(err) | |
| 250 | 新增: } | |
| 251 | 新增: defer conn.Close() | |
| 252 | 新增: conn.SetDeadline(time.Now().Add(10 * time.Second)) | |
| 253 | 新增: authorization := base64.StdEncoding.EncodeToString([]byte("cage:" + record.Token)) | |
| 254 | 新增: fmt.Fprintf(conn, "CONNECT private-web:8080 HTTP/1.1\r\nHost: private-web:8080\r\nProxy-Authorization: Basic %s\r\n\r\n", authorization) | |
| 255 | 新增: reader := bufio.NewReader(conn) | |
| 256 | 新增: connected, err := http.ReadResponse(reader, &http.Request{Method: "CONNECT"}) | |
| 257 | 新增: if err != nil || connected.StatusCode != http.StatusOK { | |
| 258 | 新增: t.Fatalf("CONNECT: %v %v", connected, err) | |
| 259 | 新增: } | |
| 260 | 新增: fmt.Fprint(conn, "GET /tunnel HTTP/1.1\r\nHost: private-web:8080\r\n\r\n") | |
| 261 | 新增: response, err = http.ReadResponse(reader, &http.Request{Method: "GET"}) | |
| 262 | 新增: if err != nil { | |
| 263 | 新增: t.Fatal(err) | |
| 264 | 新增: } | |
| 265 | 新增: body, _ := io.ReadAll(response.Body) | |
| 266 | 新增: response.Body.Close() | |
| 267 | 新增: if string(body) != "GET /tunnel " { | |
| 268 | 新增: t.Fatalf("tunnel payload: %q", body) | |
| 269 | 新增: } | |
| 270 | 新增: if _, err = n.run(ctx, request{Action: "disconnect"}); err != nil { | |
| 271 | 新增: t.Fatal(err) | |
| 272 | 新增: } | |
| 273 | 新增: if _, err = reader.ReadByte(); err == nil { | |
| 274 | 新增: t.Fatal("disconnect left tunnel alive") | |
| 275 | 新增: } | |
| 276 | 新增: if _, err = echo.Read(make([]byte, 1)); err == nil { | |
| 277 | 新增: t.Fatal("disconnect left mapped TCP alive") | |
| 278 | 新增: } | |
| 279 | 新增: if c, err := net.DialTimeout("tcp", address, time.Second); err == nil { | |
| 280 | 新增: c.Close() | |
| 281 | 新增: t.Fatal("disconnect left mapping listener alive") | |
| 282 | 新增: } | |
| 283 | 新增: n.mu.Lock() | |
| 284 | 新增: remaining := len(n.forwards) | |
| 285 | 新增: n.mu.Unlock() | |
| 286 | 新增: if remaining != 0 { | |
| 287 | 新增: t.Fatal("disconnect retained old mapping") | |
| 288 | 新增: } | |
| 289 | 新增: response, err = client.Get("http://private-web:8080/") | |
| 290 | 新增: if err != nil { | |
| 291 | 新增: t.Fatal(err) | |
| 292 | 新增: } | |
| 293 | 新增: response.Body.Close() | |
| 294 | 新增: if response.StatusCode != http.StatusBadGateway { | |
| 295 | 新增: t.Fatalf("disconnected proxy dialed: %d", response.StatusCode) | |
| 296 | 新增: } | |
| 297 | 新增:} | |
| @@ -0,0 +1,37 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "net/netip" | |
| 5 | 新增: "testing" | |
| 6 | 新增: "time" | |
| 7 | 新增: | |
| 8 | 新增: "tailscale.com/ipn/ipnstate" | |
| 9 | 新增: "tailscale.com/tailcfg" | |
| 10 | 新增: "tailscale.com/types/key" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func TestStatusShowsAccountNetworkAndDevicesWithoutPublicKeys(t *testing.T) { | |
| 14 | 新增: seen := time.Date(2026, 11, 9, 0, 0, 0, 0, time.UTC) | |
| 15 | 新增: var out state | |
| 16 | 新增: applyStatus(&out, &ipnstate.Status{ | |
| 17 | 新增: BackendState: "Running", | |
| 18 | 新增: TailscaleIPs: []netip.Addr{netip.MustParseAddr("100.88.2.3")}, | |
| 19 | 新增: CurrentTailnet: &ipnstate.TailnetStatus{Name: "work.test"}, | |
| 20 | 新增: Self: &ipnstate.PeerStatus{HostName: "cage-mac", DNSName: "cage-mac.test.ts.net.", OS: "macOS", UserID: 17}, | |
| 21 | 新增: User: map[tailcfg.UserID]tailcfg.UserProfile{17: {LoginName: "[email protected]"}}, | |
| 22 | 新增: Health: []string{"Control connection interrupted"}, | |
| 23 | 新增: Peer: map[key.NodePublic]*ipnstate.PeerStatus{ | |
| 24 | 新增: key.NewNode().Public(): {ID: "offline", HostName: "a-server", DNSName: "a-server.test.ts.net.", OS: "linux", TailscaleIPs: []netip.Addr{netip.MustParseAddr("100.88.2.5")}, LastSeen: seen}, | |
| 25 | 新增: key.NewNode().Public(): {ID: "online", HostName: "z-phone", DNSName: "z-phone.test.ts.net.", OS: "android", TailscaleIPs: []netip.Addr{netip.MustParseAddr("100.88.2.4")}, Online: true}, | |
| 26 | 新增: }, | |
| 27 | 新增: }) | |
| 28 | 新增: if out.Tailnet != "work.test" || out.Account != "[email protected]" || out.Hostname != "cage-mac" || out.OS != "macOS" || out.Name != "cage-mac.test.ts.net" { | |
| 29 | 新增: t.Fatalf("missing network identity: %+v", out) | |
| 30 | 新增: } | |
| 31 | 新增: if len(out.Peers) != 2 || !out.Peers[0].Online || out.Peers[0].OS != "android" || out.Peers[1].LastSeen == nil || !out.Peers[1].LastSeen.Equal(seen) { | |
| 32 | 新增: t.Fatalf("incorrect devices: %+v", out.Peers) | |
| 33 | 新增: } | |
| 34 | 新增: if len(out.Health) != 1 || len(out.Keys) != 0 { | |
| 35 | 新增: t.Fatal("network status must not require SSH setup") | |
| 36 | 新增: } | |
| 37 | 新增:} | |
| @@ -3,22 +3,32 @@ import { mkdir, writeFile } from "node:fs/promises"; | ||
| 3 | 3 | import { fileURLToPath } from "node:url"; |
| 4 | 4 | import { createWorkbench } from "./workbench-fixture.mjs"; |
| 5 | 5 | const engine = process.env.CAGE_TEST_BROWSER || "chromium"; |
| 6 | 删除:const output = new URL(`../../docs/test-reports/2026-11-09-tailscale/${engine}/`, import.meta.url); | |
| 6 | 新增:const output = new URL(`../../docs/test-reports/2026-11-09-tailscale-redesign/${engine}/`, import.meta.url); | |
| 7 | 7 | await mkdir(output, { recursive: true }); |
| 8 | 删除:let copied = "", fail = false, delayed = false; | |
| 9 | 删除:let tail = { installed: true, version: "1.104.5", enabled: false, backend: "Stopped", ips: [], peers: [], keys: [], user: "cage", ssh_port: 22 }; | |
| 8 | 新增:let copied = "", fail = false, delayed = false, failKey = false, failService = false, failBrowser = true; | |
| 9 | 新增:let tail = { installed: true, version: "1.104.5", enabled: false, backend: "Stopped", ips: [], peers: [], keys: [], forwards: [], user: "cage", ssh_port: 22 }; | |
| 10 | 10 | const { browser, page, state, errors } = await createWorkbench({ nativeRequest: body => { if (body.action === "clipboardWrite") { copied = body.text; return true; } } }); |
| 11 | 11 | const checks = []; |
| 12 | 12 | const open = page.getByRole("button", { name: "打开 Tailscale", exact: true }); |
| 13 | 13 | const panel = page.getByRole("dialog", { name: "Tailscale", exact: true }); |
| 14 | 新增:const refresh = () => panel.getByRole("button", { name: "刷新 Tailscale 状态" }).click(); | |
| 14 | 15 | try { |
| 16 | 新增: await page.route("**/api/browser/new", route => failBrowser ? route.fulfill({ status: 502, body: "浏览器暂未响应" }) : route.fallback()); | |
| 15 | 17 | await page.route("**/api/tailscale**", async route => { |
| 16 | 18 | const request = route.request(), action = new URL(request.url()).pathname.split("/").at(-1), body = request.postDataJSON(); |
| 17 | 19 | if (fail) return route.fulfill({ status: 502, contentType: "text/plain", body: "Tailscale 暂未响应,请稍后重试" }); |
| 18 | 20 | if (["connect", "login"].includes(action)) tail = { ...tail, enabled: true, backend: "NeedsLogin", ...(delayed ? {} : { auth_url: "https://login.tailscale.com/a/fixture-login" }) }; |
| 19 | 删除: if (action === "disconnect") tail = { ...tail, enabled: false, backend: "Stopped" }; | |
| 20 | 删除: if (action === "add-key") tail.keys.push(body.key); | |
| 21 | 新增: if (["disconnect", "logout"].includes(action)) tail = { ...tail, enabled: false, backend: "Stopped", proxy_url: "", ips: [], peers: [], forwards: [], auth_url: "" }; | |
| 22 | 新增: if (action === "add-key") { | |
| 23 | 新增: if (failKey) return route.fulfill({ status: 502, body: "请粘贴一条有效的 SSH 公钥" }); | |
| 24 | 新增: tail.keys.push(body.key); | |
| 25 | 新增: } | |
| 21 | 26 | if (action === "remove-key") tail.keys = tail.keys.filter(key => key !== body.key); |
| 27 | 新增: if (action === "open-service") { | |
| 28 | 新增: if (failService) return route.fulfill({ status: 502, body: "设备未出现在当前 Tailscale 网络中" }); | |
| 29 | 新增: assert.equal(body.host, "100.88.2.4"); assert.equal(body.port, 8080); | |
| 30 | 新增: tail.forwards = [{ host: body.host, port: body.port, address: "127.0.0.1:32123" }]; | |
| 31 | 新增: } | |
| 22 | 32 | return route.fulfill({ json: tail }); |
| 23 | 33 | }); |
| 24 | 34 | state.status.ready = state.status.vm_running = true; |
| @@ -26,41 +36,84 @@ try { | ||
| 26 | 36 | const position = await open.boundingBox(), browserPosition = await page.getByRole("button", { name: "打开浏览器", exact: true }).boundingBox(); |
| 27 | 37 | assert.ok(position.y > browserPosition.y && position.y < browserPosition.y + browserPosition.height * 2 + 8); |
| 28 | 38 | await open.focus(); await page.keyboard.press("Enter"); await panel.getByText("已断开", { exact: true }).waitFor(); |
| 29 | 删除: await panel.getByRole("button", { name: "连接 Tailscale", exact: true }).click(); | |
| 39 | 新增: assert.equal(await panel.locator("textarea").count(), 0); | |
| 40 | 新增: await panel.getByText("连接后查看你的设备", { exact: true }).waitFor(); | |
| 41 | 新增: await page.screenshot({ animations: "disabled", path: fileURLToPath(new URL("disconnected.png", output)) }); | |
| 42 | 新增: await panel.getByRole("button", { name: "连接并登录", exact: true }).click(); | |
| 43 | 新增: await panel.getByRole("alert").filter({ hasText: "登录页面未能打开" }).waitFor(); | |
| 44 | 新增: failBrowser = false; | |
| 45 | 新增: await panel.getByRole("button", { name: "打开登录页面", exact: true }).click(); | |
| 30 | 46 | await panel.waitFor({ state: "hidden" }); |
| 31 | 47 | assert.ok(state.requests.some(r => r.path === "/browser/new" && r.body.url === "https://login.tailscale.com/a/fixture-login" && r.body.incognito === false)); |
| 32 | 删除: checks.push("entry immediately follows Browser; keyboard opens panel; connect opens official auth URL in regular Cage browser"); | |
| 33 | 删除: tail = { ...tail, enabled: true, backend: "Running", name: "cage-workbench.test.ts.net", auth_url: "", ips: ["100.88.2.3"], peers: [{ name: "my-computer.test.ts.net", ip: "100.88.2.4", online: true }] }; | |
| 48 | 新增: checks.push("keyboard entry; enrollment precedes SSH; browser launch failure keeps login retry; official login opens in regular Cage browser"); | |
| 49 | 新增: const connected = { ...tail, enabled: true, backend: "Running", tailnet: "林间私网", account: "[email protected]", name: "cage-workbench.test.ts.net", hostname: "cage-workbench", os: "macOS", auth_url: "", ips: ["100.88.2.3"], proxy_url: "http://cage:[email protected]:32100", peers: [{ name: "offline-server.test.ts.net", hostname: "offline-server", os: "linux", ip: "100.88.2.5", online: false }, { name: "my-computer.test.ts.net", hostname: "my-computer", os: "macOS", ip: "100.88.2.4", online: true }] }; | |
| 50 | 新增: tail = structuredClone(connected); | |
| 34 | 51 | await open.click(); await panel.getByText("已连接", { exact: true }).waitFor(); |
| 52 | 新增: await panel.getByText("林间私网", { exact: true }).waitFor(); | |
| 53 | 新增: await panel.getByText("登录账号 · [email protected]", { exact: true }).waitFor(); | |
| 54 | 新增: assert.equal(await panel.locator(".tailscale-peer").first().getByText("my-computer", { exact: true }).count(), 1); | |
| 55 | 新增: await panel.getByLabel("搜索设备").fill("100.88.2.5"); assert.equal(await panel.locator(".tailscale-peer").count(), 1); | |
| 56 | 新增: await panel.getByLabel("搜索设备").fill("missing"); await panel.getByText("没有匹配的设备,请尝试其他名称或地址。", { exact: true }).waitFor(); | |
| 57 | 新增: await panel.getByLabel("搜索设备").fill(""); | |
| 58 | 新增: await page.screenshot({ animations: "disabled", path: fileURLToPath(new URL("connected.png", output)) }); | |
| 59 | 新增: await panel.getByRole("button", { name: "复制地址", exact: true }).click(); assert.equal(copied, "100.88.2.3"); | |
| 60 | 新增: await panel.getByRole("button", { name: "复制 my-computer 的地址", exact: true }).click(); assert.equal(copied, "100.88.2.4"); | |
| 61 | 新增: checks.push("network/account/self identity; online-first device list; name and IP search with empty feedback; address copy"); | |
| 62 | 新增: const peer = panel.locator(".tailscale-peer").first(); | |
| 63 | 新增: await peer.getByRole("button", { name: "使用设备", exact: true }).focus(); await page.keyboard.press("Enter"); | |
| 64 | 新增: await peer.getByLabel("SSH 连接", { exact: true }).fill("local-user"); | |
| 65 | 新增: await peer.getByRole("button", { name: "复制 SSH 命令", exact: true }).click(); assert.equal(copied, "ssh -l 'local-user' 100.88.2.4"); | |
| 66 | 新增: await peer.getByLabel("服务端口", { exact: true }).fill("8080"); | |
| 67 | 新增: failService = true; | |
| 68 | 新增: await peer.getByRole("button", { name: "创建连接地址", exact: true }).click(); await panel.getByRole("alert").waitFor(); | |
| 69 | 新增: assert.equal(await peer.getByLabel("服务端口").inputValue(), "8080"); | |
| 70 | 新增: failService = false; | |
| 71 | 新增: await peer.getByRole("button", { name: "创建连接地址", exact: true }).click(); | |
| 72 | 新增: await peer.getByText("127.0.0.1:32123", { exact: true }).waitFor(); | |
| 73 | 新增: await peer.getByRole("button", { name: "复制端口 8080 的连接地址", exact: true }).click(); assert.equal(copied, "127.0.0.1:32123"); | |
| 74 | 新增: await peer.getByRole("button", { name: "打开 HTTP 页面", exact: true }).click(); await panel.waitFor({ state: "hidden" }); | |
| 75 | 新增: assert.ok(state.requests.some(r => r.path === "/browser/new" && r.body.url === "http://127.0.0.1:32123")); | |
| 76 | 新增: checks.push("per-device SSH uses supplied username; service mapping errors preserve port; TCP mapping copied and HTTP page opened"); | |
| 77 | 新增: await open.click(); await panel.getByText("已连接", { exact: true }).waitFor(); | |
| 78 | 新增: await panel.getByRole("button", { name: "应用访问私网", exact: true }).click(); | |
| 79 | 新增: await panel.getByRole("button", { name: "复制私网代理地址", exact: true }).click(); assert.equal(copied, tail.proxy_url); | |
| 80 | 新增: assert.equal(await panel.getByText(tail.proxy_url, { exact: true }).count(), 0); | |
| 81 | 新增: await panel.getByRole("button", { name: "从其他设备 SSH 到 Cage", exact: true }).focus(); await page.keyboard.press("Enter"); | |
| 35 | 82 | await panel.getByRole("button", { name: "复制连接 Cage 命令" }).click(); assert.equal(copied, "ssh [email protected]"); |
| 36 | 删除: await panel.getByLabel("本机 SSH 公钥", { exact: true }).fill("ssh-ed25519 AAAAFixture local"); | |
| 37 | 删除: await panel.getByRole("button", { name: "添加公钥", exact: true }).click(); await panel.locator(".tailscale-key").waitFor(); | |
| 38 | 删除: await page.screenshot({ path: fileURLToPath(new URL("connected.png", output)) }); | |
| 83 | 新增: await panel.getByLabel("连接设备的 SSH 公钥", { exact: true }).fill("ssh-ed25519 AAAAFixture local"); | |
| 84 | 新增: failKey = true; await panel.getByRole("button", { name: "添加公钥", exact: true }).click(); await panel.getByRole("alert").waitFor(); | |
| 85 | 新增: assert.equal(await panel.getByLabel("连接设备的 SSH 公钥").inputValue(), "ssh-ed25519 AAAAFixture local"); | |
| 86 | 新增: failKey = false; await panel.getByRole("button", { name: "添加公钥", exact: true }).click(); await panel.locator(".tailscale-key").waitFor(); | |
| 87 | 新增: await page.reload(); await open.click(); await panel.getByText("已连接", { exact: true }).waitFor(); | |
| 88 | 新增: await panel.getByRole("button", { name: "从其他设备 SSH 到 Cage", exact: true }).click(); | |
| 89 | 新增: await panel.locator(".tailscale-key").waitFor(); | |
| 39 | 90 | await panel.getByRole("button", { name: "移除 SSH 公钥" }).click(); await panel.locator(".tailscale-key").waitFor({ state: "hidden" }); |
| 40 | 删除: await panel.getByRole("button", { name: "复制命令", exact: true }).click(); assert.equal(copied, "ssh 本机用户名@100.88.2.4"); | |
| 41 | 删除: checks.push("connected address, peer presence, inbound and outbound command copy, add and remove public key"); | |
| 91 | 新增: checks.push("application proxy credential copied without rendering; SSH opt-in keyboard disclosure; failed key keeps input; saved key survives refresh and can be revoked"); | |
| 42 | 92 | await page.keyboard.press("Escape"); await panel.waitFor({ state: "hidden" }); |
| 43 | 93 | await open.click(); await panel.getByRole("button", { name: "断开连接", exact: true }).click(); |
| 44 | 删除: await page.getByRole("dialog", { name: "断开 Tailscale?", exact: true }).getByRole("button", { name: "取消", exact: true }).click(); | |
| 45 | 删除: assert.equal(tail.enabled, true); | |
| 94 | 新增: await page.getByRole("dialog", { name: "断开 Tailscale?", exact: true }).getByRole("button", { name: "取消", exact: true }).click(); assert.equal(tail.enabled, true); | |
| 46 | 95 | await panel.getByRole("button", { name: "断开连接", exact: true }).click(); |
| 47 | 96 | await page.getByRole("dialog", { name: "断开 Tailscale?", exact: true }).getByRole("button", { name: "断开连接", exact: true }).click(); |
| 48 | 删除: await panel.getByText("已断开", { exact: true }).waitFor(); | |
| 49 | 删除: checks.push("closing and reopening retains status; cancel preserves active connection; explicit disconnect closes connection"); | |
| 97 | 新增: await panel.getByText("已断开", { exact: true }).waitFor(); assert.equal(await panel.locator("textarea").count(), 0); | |
| 50 | 98 | delayed = true; delete tail.auth_url; |
| 51 | 删除: await panel.getByRole("button", { name: "连接 Tailscale", exact: true }).click(); | |
| 52 | 删除: await panel.getByText("等待登录", { exact: true }).waitFor(); | |
| 53 | 删除: tail.auth_url = "https://login.tailscale.com/a/delayed-login"; | |
| 54 | 删除: await panel.waitFor({ state: "hidden" }); | |
| 99 | 新增: await panel.getByRole("button", { name: "连接并登录", exact: true }).click(); await panel.getByText("等待登录", { exact: true }).waitFor(); | |
| 100 | 新增: tail.auth_url = "https://login.tailscale.com/a/delayed-login"; await panel.waitFor({ state: "hidden" }); | |
| 55 | 101 | assert.ok(state.requests.some(r => r.path === "/browser/new" && r.body.url === tail.auth_url)); |
| 56 | 删除: checks.push("asynchronously generated auth URL opens without a second login click"); | |
| 57 | 删除: fail = true; await open.click(); await panel.getByRole("alert").waitFor(); assert.ok(await panel.getByRole("alert").textContent()); | |
| 58 | 删除: fail = false; await panel.getByRole("button", { name: "刷新 Tailscale 状态" }).click(); await panel.getByRole("alert").waitFor({ state: "hidden" }); | |
| 102 | 新增: tail = { ...tail, auth_url: "", backend: "NeedsMachineAuth" }; await open.click(); await panel.getByText("等待管理员批准", { exact: true }).waitFor(); | |
| 103 | 新增: assert.equal(await panel.getByRole("button", { name: "重新发起登录", exact: true }).count(), 0); | |
| 104 | 新增: checks.push("disconnect cancellation preserves network; confirmation clears device controls; delayed auth URL opens automatically; approval is distinct from login"); | |
| 105 | 新增: tail = { ...connected, peers: [], forwards: [] }; await refresh(); await panel.getByText("私网已连接,还没有发现其他设备", { exact: true }).waitFor(); | |
| 106 | 新增: fail = true; await refresh(); await panel.getByRole("alert").waitFor(); fail = false; await refresh(); await panel.getByRole("alert").waitFor({ state: "hidden" }); | |
| 107 | 新增: tail = structuredClone(connected); await refresh(); | |
| 59 | 108 | await page.setViewportSize({ width: 820, height: 600 }); |
| 60 | 删除: await page.screenshot({ path: fileURLToPath(new URL("compact.png", output)) }); | |
| 109 | 新增: await page.screenshot({ animations: "disabled", path: fileURLToPath(new URL("compact.png", output)) }); | |
| 110 | 新增: assert.ok(await panel.evaluate(node => node.scrollWidth <= node.clientWidth + 1)); | |
| 111 | 新增: await page.setViewportSize({ width: 520, height: 700 }); | |
| 112 | 新增: await panel.locator(".tailscale-peer").first().getByRole("button", { name: "使用设备", exact: true }).click(); | |
| 113 | 新增: await page.screenshot({ animations: "disabled", path: fileURLToPath(new URL("narrow.png", output)) }); | |
| 61 | 114 | assert.ok(await panel.evaluate(node => node.scrollWidth <= node.clientWidth + 1)); |
| 62 | 115 | assert.deepEqual(errors, []); |
| 63 | 删除: checks.push("service failure is actionable, refresh recovers, compact panel has no horizontal overflow, no browser exceptions"); | |
| 116 | 新增: checks.push("connected empty list guides adding device; API error refresh recovery; compact and narrow layouts have no horizontal overflow; no browser exceptions"); | |
| 64 | 117 | await writeFile(new URL("result.json", output), JSON.stringify({ engine, checks, errors }, null, 2)); |
| 65 | 118 | console.log(JSON.stringify({ engine, checks, errors }, null, 2)); |
| 66 | 119 | } finally { await browser.close(); } |
| @@ -1754,7 +1754,7 @@ function App() { | ||
| 1754 | 1754 | if (nativeGuest && !await confirm({ title: "更新环境组件?", body: "更新会重新连接浏览器和显示组件,请先保存工作。设备身份、公钥和个人数据保留。", confirm: "更新组件" })) return; |
| 1755 | 1755 | await action(nativeGuest ? "/environment/update" : "/tailscale/install", {}); |
| 1756 | 1756 | }} |
| 1757 | 删除: onOpenBrowser={async url => { const result = await openBrowserPage(url, false); if (result) setTailscaleOpen(false); }} />} | |
| 1757 | 新增: onOpenBrowser={async url => { const result = await openBrowserPage(url, false); if (result) setTailscaleOpen(false); return Boolean(result); }} />} | |
| 1758 | 1758 | {projectDialog && ( |
| 1759 | 1759 | <ProjectDialog |
| 1760 | 1760 | current={settings} |
| @@ -1,19 +1,71 @@ | ||
| 1 | 删除:.tailscale-panel { display: flex; flex-direction: column; gap: 16px; } | |
| 2 | 删除:.tailscale-panel > .field-help { margin: 0; } | |
| 1 | 新增:.tailscale-panel { display: flex; flex-direction: column; gap: 20px; } | |
| 2 | 新增:.tailscale-overview { padding: 18px; border: 1px solid var(--border); border-radius: 12px; background: var(--chrome); } | |
| 3 | 3 | .tailscale-state { display: flex; align-items: center; gap: 12px; } |
| 4 | 删除:.tailscale-state > div { flex: 1; min-width: 0; } | |
| 5 | 删除:.tailscale-state strong, .tailscale-state span, .tailscale-peer strong, .tailscale-peer span { display: block; overflow-wrap: anywhere; } | |
| 6 | 删除:.tailscale-state span, .tailscale-peer span { font-size: 12px; color: var(--muted); margin-top: 4px; } | |
| 7 | 删除:.tailscale-actions { display: flex; flex-wrap: wrap; gap: 8px; } | |
| 8 | 删除:.tailscale-section { display: flex; flex-direction: column; gap: 10px; min-width: 0; border-top: 1px solid var(--border); padding-top: 16px; } | |
| 4 | 新增:.tailscale-state > div:nth-child(2) { flex: 1; min-width: 0; } | |
| 5 | 新增:.tailscale-network-icon { display: flex; padding: 10px; background: var(--hover); border-radius: 10px; } | |
| 6 | 新增:.connected .tailscale-network-icon { color: var(--accent); } | |
| 7 | 新增:.tailscale-state strong { display: block; font-size: 17px; } | |
| 8 | 新增:.tailscale-state span, .tailscale-peer-info span, .tailscale-address { display: block; color: var(--muted); font-size: 12px; margin-top: 4px; overflow-wrap: anywhere; } | |
| 9 | 新增:.tailscale-overview > .field-help { margin: 14px 0 0; } | |
| 10 | 新增:.tailscale-account { color: var(--muted); font-size: 12px; margin: 8px 0 0; overflow-wrap: anywhere; } | |
| 11 | 新增:.tailscale-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 16px; } | |
| 12 | 新增:.tailscale-section { display: flex; flex-direction: column; gap: 12px; min-width: 0; border-top: 1px solid var(--border); padding-top: 18px; } | |
| 9 | 13 | .tailscale-section h3 { margin: 0; font-size: 14px; } |
| 14 | 新增:.tailscale-section h3 > span { margin-left: 8px; color: var(--muted); font-weight: 400; } | |
| 10 | 15 | .tailscale-section .field-help { margin: 0; } |
| 11 | 删除:.tailscale-section .field-label { display: flex; align-items: center; gap: 6px; } | |
| 12 | 删除:.tailscale-section textarea { width: 100%; resize: vertical; min-height: 72px; font-family: var(--font-mono, monospace); font-size: 12px; border: 1px solid var(--border); border-radius: 7px; background: var(--panel, transparent); color: inherit; padding: 9px 10px; } | |
| 13 | 删除:.tailscale-section > button { align-self: flex-start; } | |
| 14 | 删除:.tailscale-command, .tailscale-key, .tailscale-peer { display: flex; align-items: center; gap: 8px; min-width: 0; } | |
| 16 | 新增:.tailscale-section-heading { display: flex; justify-content: space-between; gap: 10px; align-items: center; } | |
| 17 | 新增:.tailscale-self, .tailscale-peer-row { display: flex; align-items: center; gap: 12px; min-width: 0; } | |
| 18 | 新增:.tailscale-self > div, .tailscale-peer-info { flex: 1; min-width: 0; } | |
| 19 | 新增:.tailscale-self strong, .tailscale-peer-info strong { font-size: 13px; overflow-wrap: anywhere; } | |
| 20 | 新增:.tailscale-self { padding: 0 2px; } | |
| 21 | 新增:.tailscale-badge { display: inline-block; font-size: 10px; font-weight: 400; padding: 2px 6px; margin-left: 5px; border-radius: 4px; color: var(--muted); border: 1px solid var(--border); } | |
| 22 | 新增:.tailscale-search { display: flex; gap: 8px; align-items: center; color: var(--muted); border: 1px solid var(--border); border-radius: 7px; padding: 0 10px; } | |
| 23 | 新增:.tailscale-search input { width: 100%; border: 0; background: transparent; padding: 10px 0; font: inherit; color: var(--ink); outline-offset: 2px; min-width: 0; } | |
| 24 | 新增:.tailscale-empty { display: flex; flex-direction: column; align-items: center; gap: 10px; text-align: center; color: var(--muted); padding: 28px 20px; background: var(--chrome); border-radius: 8px; } | |
| 25 | 新增:.tailscale-empty strong { font-size: 13px; font-weight: 500; color: var(--ink); } | |
| 26 | 新增:.tailscale-empty p { margin: 0; max-width: 390px; font-size: 12px; line-height: 1.7; } | |
| 27 | 新增:.tailscale-peers { display: flex; flex-direction: column; } | |
| 28 | 新增:.tailscale-peer { border-bottom: 1px solid var(--border); padding: 13px 0; } | |
| 29 | 新增:.tailscale-peer:last-child { border-bottom: 0; padding-bottom: 0; } | |
| 30 | 新增:.tailscale-peer-row > svg, .tailscale-self > svg { flex-shrink: 0; color: var(--muted); } | |
| 31 | 新增:.tailscale-peer-row button { flex-shrink: 0; } | |
| 32 | 新增:.tailscale-presence { display: flex; align-items: center; gap: 5px; white-space: nowrap; color: var(--muted); font-size: 11px; } | |
| 33 | 新增:.tailscale-presence i { display: block; width: 6px; height: 6px; border-radius: 50%; background: var(--muted); } | |
| 34 | 新增:.tailscale-presence.online i { background: #528267; } | |
| 35 | 新增:.tailscale-device-detail { display: flex; flex-direction: column; gap: 10px; padding: 16px; margin-top: 12px; background: var(--chrome); border: 1px solid var(--border); border-radius: 8px; } | |
| 36 | 新增:.tailscale-dns { overflow-wrap: anywhere; } | |
| 37 | 新增:.tailscale-connect-form { display: flex; gap: 8px; } | |
| 38 | 新增:.tailscale-connect-form input { min-width: 0; flex: 1; border: 1px solid var(--border); border-radius: 7px; padding: 8px 10px; background: transparent; color: var(--ink); font: inherit; font-size: 12px; } | |
| 39 | 新增:.tailscale-disclosure { display: flex; align-items: center; justify-content: space-between; gap: 10px; border: 0; background: transparent; padding: 0; width: 100%; color: inherit; cursor: pointer; font: inherit; font-size: 13px; font-weight: 600; text-align: left; } | |
| 40 | 新增:.tailscale-disclosure > span, .tailscale-detail .field-label { display: flex; align-items: center; gap: 8px; } | |
| 41 | 新增:.tailscale-disclosure > svg, .tailscale-peer-row button > svg { transition: transform 160ms ease; } | |
| 42 | 新增:.tailscale-disclosure[aria-expanded="true"] > svg, .tailscale-peer-row button[aria-expanded="true"] > svg { transform: rotate(180deg); } | |
| 43 | 新增:.tailscale-detail { display: flex; flex-direction: column; gap: 10px; } | |
| 44 | 新增:.tailscale-detail > button { align-self: flex-start; } | |
| 45 | 新增:.tailscale-detail textarea { width: 100%; resize: vertical; min-height: 72px; font-family: var(--font-mono, monospace); font-size: 12px; border: 1px solid var(--border); border-radius: 7px; background: var(--chrome); color: inherit; padding: 9px 10px; } | |
| 46 | 新增:.tailscale-command, .tailscale-key { display: flex; align-items: center; gap: 8px; min-width: 0; } | |
| 15 | 47 | .tailscale-command { border: 1px solid var(--border); border-radius: 7px; padding: 7px 10px; } |
| 16 | 删除:.tailscale-command code, .tailscale-peer > div { flex: 1; min-width: 0; overflow-wrap: anywhere; } | |
| 17 | 删除:.tailscale-keys, .tailscale-peers { display: flex; flex-direction: column; gap: 10px; } | |
| 48 | 新增:.tailscale-command code { flex: 1; min-width: 0; overflow-wrap: anywhere; } | |
| 49 | 新增:.tailscale-keys { display: flex; flex-direction: column; gap: 10px; } | |
| 18 | 50 | .tailscale-key code { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 12px; } |
| 19 | 删除:.tailscale-peer .quiet-button { flex-shrink: 0; } | |
| 51 | 新增:.tailscale-panel > .tailscale-footer { margin: 0; font-size: 11px; line-height: 1.7; } | |
| 52 | 新增:.tailscale-notice { display: flex; gap: 6px; align-items: center; font-size: 12px; margin: 0; color: var(--accent); } | |
| 53 | 新增:.tailscale-health { border-left: 2px solid var(--accent); padding: 0 12px; font-size: 12px; } | |
| 54 | 新增:.tailscale-health p { margin: 6px 0 0; overflow-wrap: anywhere; } | |
| 55 | 新增:@media (max-width: 600px) { | |
| 56 | 新增: .tailscale-panel { gap: 16px; } | |
| 57 | 新增: .tailscale-overview { padding: 14px; } | |
| 58 | 新增: .tailscale-peer-row { flex-wrap: wrap; gap: 9px; } | |
| 59 | 新增: .tailscale-peer-info { flex-basis: calc(100% - 100px); } | |
| 60 | 新增: .tailscale-presence { margin-left: 32px; } | |
| 61 | 新增: .tailscale-connect-form { flex-direction: column; } | |
| 62 | 新增: .tailscale-self { flex-wrap: wrap; } | |
| 63 | 新增:} | |
| 64 | 新增:@media (prefers-reduced-motion: reduce) { | |
| 65 | 新增: .tailscale-disclosure > svg, .tailscale-peer-row button > svg { transition: none; } | |
| 66 | 新增:} | |
| 67 | 新增:.tailscale-forward { display: flex; align-items: center; gap: 8px; border: 1px solid var(--border); border-radius: 7px; padding: 9px 10px; } | |
| 68 | 新增:.tailscale-forward > span { flex: 1; min-width: 0; } | |
| 69 | 新增:.tailscale-forward strong { display: block; font-size: 11px; margin-bottom: 4px; } | |
| 70 | 新增:.tailscale-forward code { font-size: 12px; overflow-wrap: anywhere; } | |
| 71 | 新增:@media (max-width: 600px) { .tailscale-forward { flex-wrap: wrap; } } | |
| @@ -1,27 +1,55 @@ | ||
| 1 | 1 | import React, { useEffect, useRef, useState } from "react"; |
| 2 | 删除:import { Copy, KeyRound, LoaderCircle, Network, RefreshCw, Trash2 } from "lucide-react"; | |
| 2 | 新增:import { Check, ChevronDown, Copy, ExternalLink, KeyRound, LoaderCircle, Monitor, Network, RefreshCw, Search, Smartphone, Terminal, Trash2 } from "lucide-react"; | |
| 3 | 3 | import { api, writeClipboard } from "./api"; |
| 4 | 4 | import { Modal } from "./modal"; |
| 5 | 5 | import "./tailscale.css"; |
| 6 | 6 | |
| 7 | 删除:const labels = { Running: "已连接", NeedsLogin: "等待登录", NeedsMachineAuth: "等待管理员批准设备", Starting: "正在连接", Stopped: "已断开", NotInstalled: "尚未安装" }; | |
| 7 | 新增:const labels = { Running: "已连接", NeedsLogin: "等待登录", NeedsMachineAuth: "等待管理员批准", Starting: "正在连接", Stopped: "已断开", NotInstalled: "尚未安装" }; | |
| 8 | 新增:const descriptions = { | |
| 9 | 新增: Stopped: "登录 Tailscale,让 Cage 加入你的私网。其他设备加入同一网络后,会显示在这里。", | |
| 10 | 新增: NeedsLogin: "在打开的 Tailscale 官方页面完成登录并授权此设备,然后返回这里。", | |
| 11 | 新增: NeedsMachineAuth: "登录已完成。请让此网络的管理员在 Tailscale 管理台批准 Cage 设备。", | |
| 12 | 新增: Starting: "正在连接 Tailscale,设备清单会在连接成功后自动更新。", | |
| 13 | 新增:}; | |
| 14 | 新增:const deviceName = peer => peer.hostname || peer.name?.split(".")[0] || peer.ip; | |
| 15 | 新增:function DeviceIcon({ os }) { return ["android", "iOS"].includes(os) ? <Smartphone size={20} /> : <Monitor size={20} />; } | |
| 16 | 新增: | |
| 8 | 17 | export function TailscalePanel({ status, onClose, onOpenBrowser, onInstall, onConfirm }) { |
| 9 | 删除: const [state, setState] = useState(null), [error, setError] = useState(""), [busy, setBusy] = useState(false), [key, setKey] = useState(""), [notice, setNotice] = useState(""); | |
| 18 | 新增: const [state, setState] = useState(null), [error, setError] = useState(""), [busy, setBusy] = useState(false); | |
| 19 | 新增: const [key, setKey] = useState(""), [notice, setNotice] = useState(""), [query, setQuery] = useState(""); | |
| 20 | 新增: const [sshOpen, setSSHOpen] = useState(false), [selected, setSelected] = useState(""), [username, setUsername] = useState(""); | |
| 21 | 新增: const [port, setPort] = useState("80"), [appsOpen, setAppsOpen] = useState(false); | |
| 10 | 22 | const mounted = useRef(true), inflight = useRef(false), loginRequested = useRef(false), revision = useRef(0); |
| 11 | 23 | const ready = status.ready && !status.job?.running; |
| 24 | 新增: const connected = ready && state?.backend === "Running"; | |
| 25 | 新增: const address = state?.ips?.find(ip => !ip.includes(":")); | |
| 26 | 新增: const peers = [...(state?.peers || [])].sort((a, b) => Number(b.online) - Number(a.online) || deviceName(a).localeCompare(deviceName(b))); | |
| 27 | 新增: const visible = peers.filter(peer => [deviceName(peer), peer.name, peer.ip, peer.os].some(value => value?.toLowerCase().includes(query.trim().toLowerCase()))); | |
| 28 | 新增: const openLogin = async url => { | |
| 29 | 新增: loginRequested.current = false; | |
| 30 | 新增: try { if (await onOpenBrowser(url) === false && mounted.current) setError("登录页面未能打开,请点击“打开登录页面”重试。"); } | |
| 31 | 新增: catch { if (mounted.current) setError("登录页面未能打开,请点击“打开登录页面”重试。"); } | |
| 32 | 新增: }; | |
| 12 | 33 | const refresh = async () => { |
| 13 | 34 | if (inflight.current || !ready) return; |
| 14 | 35 | inflight.current = true; |
| 15 | 36 | const current = ++revision.current; |
| 16 | 删除: try { const value = await api("/tailscale"); if (mounted.current && current === revision.current) { setState(value); setError(""); if (loginRequested.current && value.auth_url) { loginRequested.current = false; await onOpenBrowser(value.auth_url); } } return value; } | |
| 17 | 删除: catch (e) { if (mounted.current) setError(e.message); } | |
| 37 | 新增: try { | |
| 38 | 新增: const value = await api("/tailscale"); | |
| 39 | 新增: if (mounted.current && current === revision.current) { | |
| 40 | 新增: setState(value); setError(""); | |
| 41 | 新增: if (loginRequested.current && value.auth_url) await openLogin(value.auth_url); | |
| 42 | 新增: if (value.backend === "Running") loginRequested.current = false; | |
| 43 | 新增: } | |
| 44 | 新增: return value; | |
| 45 | 新增: } catch (e) { if (mounted.current) setError(e.message); } | |
| 18 | 46 | finally { inflight.current = false; } |
| 19 | 47 | }; |
| 20 | 48 | useEffect(() => { |
| 21 | 49 | mounted.current = true; |
| 22 | 50 | void refresh(); |
| 23 | 51 | const timer = setInterval(() => void refresh(), 3000); |
| 24 | 删除: return () => { mounted.current = false; clearInterval(timer); }; | |
| 52 | 新增: return () => { mounted.current = false; revision.current++; clearInterval(timer); }; | |
| 25 | 53 | }, [ready]); |
| 26 | 54 | const act = async (action, body = {}) => { |
| 27 | 55 | if (busy) return; |
| @@ -37,58 +65,93 @@ export function TailscalePanel({ status, onClose, onOpenBrowser, onInstall, onCo | ||
| 37 | 65 | const login = async () => { |
| 38 | 66 | loginRequested.current = true; |
| 39 | 67 | const result = await act(state?.enabled ? "login" : "connect"); |
| 40 | 删除: if (result?.auth_url) { loginRequested.current = false; await onOpenBrowser(result.auth_url); } | |
| 68 | 新增: if (result?.auth_url) await openLogin(result.auth_url); | |
| 41 | 69 | else if (!result || result.backend === "Running") loginRequested.current = false; |
| 42 | 70 | }; |
| 43 | 删除: const copy = async text => { | |
| 44 | 删除: try { await writeClipboard(text); setNotice("已复制"); } | |
| 45 | 删除: catch { setNotice("请选中命令后复制"); } | |
| 71 | 新增: const copy = async (text, message = "已复制") => { | |
| 72 | 新增: try { await writeClipboard(text); setNotice(message); } | |
| 73 | 新增: catch { setNotice("复制失败,请选中文本手动复制。"); } | |
| 74 | 新增: }; | |
| 75 | 新增: const stop = async logout => { | |
| 76 | 新增: if (!await onConfirm({ title: logout ? "退出 Tailscale 登录?" : "断开 Tailscale?", body: logout ? "私网连接会中断,下次连接需要重新登录。已添加的 SSH 公钥保留。" : "正在使用的私网连接会中断,登录状态和 SSH 公钥保留。", confirm: logout ? "退出登录" : "断开连接" })) return; | |
| 77 | 新增: loginRequested.current = false; | |
| 78 | 新增: if (await act(logout ? "logout" : "disconnect")) { setSelected(""); setSSHOpen(false); } | |
| 46 | 79 | }; |
| 47 | 删除: const address = state?.ips?.find(ip => !ip.includes(":")); | |
| 48 | 删除: const connected = state?.backend === "Running"; | |
| 49 | 80 | return <Modal title="Tailscale" onClose={onClose} wide> |
| 50 | 81 | <div className="modal-body tailscale-panel"> |
| 51 | 删除: <p className="field-help">让 Cage 与本机加入同一私网,通过 SSH 双向连接。本机也需安装 Tailscale 并加入同一网络。</p> | |
| 52 | 删除: <div className="tailscale-state" role="status"> | |
| 53 | 删除: <Network size={20} /> | |
| 54 | 删除: <div><strong>{!ready ? "等待 Cage 环境就绪" : labels[state?.backend] || (state ? "连接状态待确认" : "正在读取状态…")}</strong> | |
| 55 | 删除: {state?.name && <span>{state.name}</span>} | |
| 82 | 新增: <div className={`tailscale-overview${connected ? " connected" : ""}`}> | |
| 83 | 新增: <div className="tailscale-state" role="status"> | |
| 84 | 新增: <div className="tailscale-network-icon"><Network size={24} /></div> | |
| 85 | 新增: <div><strong>{!ready ? "等待 Cage 环境就绪" : labels[state?.backend] || (state ? "连接状态待确认" : "正在读取状态…")}</strong> | |
| 86 | 新增: <span>{connected ? (state.tailnet || "Tailscale 私网") : "你的设备,连接在一起"}</span> | |
| 87 | 新增: </div> | |
| 88 | 新增: <button className="icon-button" aria-label="刷新 Tailscale 状态" disabled={!ready || busy} onClick={refresh}><RefreshCw size={16} /></button> | |
| 56 | 89 | </div> |
| 57 | 删除: <button className="icon-button" aria-label="刷新 Tailscale 状态" disabled={!ready || busy} onClick={refresh}><RefreshCw size={16} /></button> | |
| 90 | 新增: <p className="field-help">{!ready ? "启动 Cage 环境后,即可登录并连接私网。" : connected ? "Cage 已加入私网。选择设备,查看地址并使用它的服务。" : descriptions[state?.backend] || "正在读取当前环境的 Tailscale 状态。"}</p> | |
| 91 | 新增: {state?.account && connected && <p className="tailscale-account">登录账号 · {state.account}</p>} | |
| 92 | 新增: {ready && state && <div className="tailscale-actions"> | |
| 93 | 新增: {!state.installed ? <button className="primary-button" disabled={busy} onClick={async () => { | |
| 94 | 新增: setBusy(true); setError(""); | |
| 95 | 新增: try { await onInstall(); } catch (e) { setError(e.message); } | |
| 96 | 新增: finally { if (mounted.current) setBusy(false); } | |
| 97 | 新增: }}>{["macos", "windows-11"].includes(status.guest_system) ? "更新环境组件以安装" : "安装 Tailscale"}</button> : <> | |
| 98 | 新增: {!connected && !["NeedsMachineAuth", "Starting"].includes(state.backend) && <button className="primary-button" disabled={busy} onClick={login}>{busy ? <LoaderCircle size={15} className="spin" /> : <ExternalLink size={15} />}{state.enabled ? "重新发起登录" : "连接并登录"}</button>} | |
| 99 | 新增: {state.auth_url && !connected && <button className="quiet-button" disabled={busy} onClick={() => openLogin(state.auth_url)}>打开登录页面</button>} | |
| 100 | 新增: {state.enabled && <button className="quiet-button" disabled={busy} onClick={() => stop(false)}>断开连接</button>} | |
| 101 | 新增: {connected && <button className="quiet-button" disabled={busy} onClick={() => stop(true)}>退出登录</button>} | |
| 102 | 新增: </>} | |
| 103 | 新增: </div>} | |
| 58 | 104 | </div> |
| 59 | 105 | {error && <p className="error-message" role="alert">{error}</p>} |
| 60 | 删除: {ready && state && <div className="tailscale-actions"> | |
| 61 | 删除: {!state.installed ? <button className="primary-button" disabled={busy} onClick={async () => { setBusy(true); try { await onInstall(); } finally { inflight.current = false; if (mounted.current) setBusy(false); } }}>{["macos", "windows-11"].includes(status.guest_system) ? "更新环境组件以安装" : "安装 Tailscale"}</button> | |
| 62 | 删除: : <> | |
| 63 | 删除: {!connected && <button className="primary-button" disabled={busy} onClick={login}>{busy && <LoaderCircle size={15} className="spin" />}{state.enabled ? "在浏览器登录" : "连接 Tailscale"}</button>} | |
| 64 | 删除: {state.auth_url && <button className="quiet-button" disabled={busy} onClick={() => onOpenBrowser(state.auth_url)}>打开登录页面</button>} | |
| 65 | 删除: {state.enabled && <button className="quiet-button" disabled={busy} onClick={async () => { | |
| 66 | 删除: if (await onConfirm({ title: "断开 Tailscale?", body: "正在使用的私网 SSH 连接会中断,登录状态和公钥保留。", confirm: "断开连接" })) await act("disconnect"); | |
| 67 | 删除: }}>断开连接</button>} | |
| 68 | 删除: {(state.enabled || state.ips?.length > 0) && <button className="quiet-button" disabled={busy} onClick={async () => { | |
| 69 | 删除: if (await onConfirm({ title: "退出 Tailscale 登录?", body: "私网 SSH 连接会中断,下次连接需要重新登录。已添加的 SSH 公钥保留。", confirm: "退出登录" })) await act("logout"); | |
| 70 | 删除: }}>退出登录</button>} | |
| 71 | 删除: </>} | |
| 72 | 删除: </div>} | |
| 73 | 删除: {state?.installed && <> | |
| 74 | 删除: <section className="tailscale-section"> | |
| 75 | 删除: <h3>本机连接 Cage</h3> | |
| 76 | 删除: <p className="field-help">添加本机的 SSH 公钥后,在本机终端执行下面的命令。私钥留在本机。</p> | |
| 77 | 删除: {address ? <div className="tailscale-command"><code>{`ssh ${state.user}@${address}`}</code><button className="icon-button" aria-label="复制连接 Cage 命令" onClick={() => copy(`ssh ${state.user}@${address}`)}><Copy size={15} /></button></div> : <p className="field-help">连接成功后显示 Cage 的私网地址。</p>} | |
| 78 | 删除: <label className="field-label" htmlFor="tailscale-key"><KeyRound size={14} /> 本机 SSH 公钥</label> | |
| 79 | 删除: <textarea className="tailscale-key-input" id="tailscale-key" rows={3} placeholder="ssh-ed25519 AAAA…" value={key} onChange={e => setKey(e.target.value)} maxLength={8192} spellCheck={false} /> | |
| 80 | 删除: <button className="quiet-button" disabled={!ready || busy || !key.trim()} onClick={() => act("add-key", { key: key.trim() })}>添加公钥</button> | |
| 81 | 删除: <div className="tailscale-keys">{state.keys.map(entry => <div className="tailscale-key" key={entry}><code title={entry}>{entry}</code><button className="icon-button" disabled={!ready || busy} aria-label="移除 SSH 公钥" onClick={() => act("remove-key", { key: entry })}><Trash2 size={14} /></button></div>)}</div> | |
| 82 | 删除: </section> | |
| 83 | 删除: <section className="tailscale-section"> | |
| 84 | 删除: <h3>Cage 连接本机</h3> | |
| 85 | 删除: <p className="field-help">本机开启远程登录或 SSH 服务,再在 Cage 终端执行 <code>ssh 本机用户名@私网地址</code>,按本机 SSH 的认证方式登录。</p> | |
| 86 | 删除: {connected && state.peers.length === 0 && <p className="field-help">尚未发现其他设备,请确认本机已加入同一 Tailscale 网络。</p>} | |
| 87 | 删除: <div className="tailscale-peers">{state.peers.map(peer => <div className="tailscale-peer" key={peer.ip}><div><strong>{peer.name}</strong><span>{peer.ip} · {peer.online ? "在线" : "离线"}</span></div><button className="quiet-button" onClick={() => copy(`ssh 本机用户名@${peer.ip}`)}>复制命令</button></div>)}</div> | |
| 88 | 删除: </section> | |
| 89 | 删除: <p className="field-help">私网连接仍受 Tailscale 访问规则控制。Cage 暂停外网、停止环境或退出后台时会断开私网;重新连接沿用设备身份。公网 UDP 受限时通过 Tailscale 中继传输。</p> | |
| 90 | 删除: </>} | |
| 91 | 删除: {notice && <p role="status">{notice}</p>} | |
| 106 | 新增: {connected && state.health?.length > 0 && <div className="tailscale-health" role="status"><strong>网络需要留意</strong>{state.health.map((message, i) => <p key={i}>{message}</p>)}</div>} | |
| 107 | 新增: {connected && <section className="tailscale-self" aria-label="当前 Cage 设备"> | |
| 108 | 新增: <DeviceIcon os={state.os} /> | |
| 109 | 新增: <div><strong>{state.hostname || state.name?.split(".")[0] || "Cage"} <span className="tailscale-badge">当前环境</span></strong><span className="tailscale-address">{address || "正在分配地址…"}{state.os ? ` · ${state.os}` : ""}</span></div> | |
| 110 | 新增: {address && <button className="quiet-button" onClick={() => copy(address, "已复制 Cage 私网地址")}><Copy size={14} />复制地址</button>} | |
| 111 | 新增: </section>} | |
| 112 | 新增: <section className="tailscale-section tailscale-devices" aria-labelledby="tailscale-devices-title"> | |
| 113 | 新增: <div className="tailscale-section-heading"><h3 id="tailscale-devices-title">网络中的设备{connected && <span>{peers.length}</span>}</h3>{connected && peers.length > 0 && <span className="field-help">{peers.filter(peer => peer.online).length} 台在线</span>}</div> | |
| 114 | 新增: {connected && peers.length > 0 && <label className="tailscale-search"><Search size={16} /><input aria-label="搜索设备" type="search" placeholder="搜索设备名称或地址" value={query} onChange={e => setQuery(e.target.value)} /></label>} | |
| 115 | 新增: {!connected ? <div className="tailscale-empty"><Monitor size={26} /><strong>连接后查看你的设备</strong><p>在浏览器完成登录,设备清单会自动出现。</p></div> | |
| 116 | 新增: : peers.length === 0 ? <div className="tailscale-empty"><Monitor size={26} /><strong>私网已连接,还没有发现其他设备</strong><p>在电脑或手机安装 Tailscale,并加入同一网络。这里只显示此网络允许 Cage 发现的设备。</p></div> | |
| 117 | 新增: : visible.length === 0 ? <p className="tailscale-empty">没有匹配的设备,请尝试其他名称或地址。</p> | |
| 118 | 新增: : <div className="tailscale-peers">{visible.map(peer => <article className="tailscale-peer" key={peer.id || peer.ip}> | |
| 119 | 新增: <div className="tailscale-peer-row"><DeviceIcon os={peer.os} /><div className="tailscale-peer-info"><strong>{deviceName(peer)}</strong><span>{peer.ip}{peer.os ? ` · ${peer.os}` : ""}</span></div> | |
| 120 | 新增: <span className={`tailscale-presence${peer.online ? " online" : ""}`}><i />{peer.online ? "在线" : "离线"}</span> | |
| 121 | 新增: <button className="icon-button" aria-label={`复制 ${deviceName(peer)} 的地址`} onClick={() => copy(peer.ip, "已复制设备私网地址")}><Copy size={15} /></button> | |
| 122 | 新增: <button className="quiet-button" aria-expanded={selected === peer.ip} aria-controls={`tailnet-device-${peer.ip}`} onClick={() => { setSelected(selected === peer.ip ? "" : peer.ip); setUsername(""); setPort("80"); }}>使用设备<ChevronDown size={14} /></button> | |
| 123 | 新增: </div> | |
| 124 | 新增: {selected === peer.ip && <div className="tailscale-device-detail" id={`tailnet-device-${peer.ip}`}> | |
| 125 | 新增: {peer.name && <p className="field-help tailscale-dns">{peer.name}</p>} | |
| 126 | 新增: {!peer.online && <p className="field-help">设备当前离线,请先在该设备上连接 Tailscale。</p>} | |
| 127 | 新增: <label className="field-label" htmlFor="tailnet-service-port">访问设备上的服务</label> | |
| 128 | 新增: <p className="field-help">填写服务端口,为 Cage 内的浏览器、数据库客户端或其他应用创建本地连接地址。</p> | |
| 129 | 新增: <div className="tailscale-connect-form"><input id="tailnet-service-port" aria-label="服务端口" type="number" min="1" max="65535" inputMode="numeric" value={port} onChange={e => setPort(e.target.value)} /><button className="quiet-button" disabled={busy || !Number.isInteger(Number(port)) || Number(port) < 1 || Number(port) > 65535} onClick={async () => { if (await act("open-service", { host: peer.ip, port: Number(port) })) setNotice("本地连接地址已就绪,请在 Cage 环境内使用。"); }}>创建连接地址</button></div> | |
| 130 | 新增: {(state.forwards || []).filter(entry => entry.host === peer.ip).map(entry => <div className="tailscale-forward" key={`${entry.host}:${entry.port}`}><span><strong>端口 {entry.port}</strong><code>{entry.address}</code></span><button className="icon-button" aria-label={`复制端口 ${entry.port} 的连接地址`} onClick={() => copy(entry.address, "已复制 Cage 内可用的连接地址")}><Copy size={14} /></button><button className="quiet-button" onClick={async () => { try { if (await onOpenBrowser(`http://${entry.address}`) === false) setError("服务页面未能打开,请重试。"); } catch { setError("服务页面未能打开,请重试。"); } }}>打开 HTTP 页面</button></div>)} | |
| 131 | 新增: <label className="field-label" htmlFor="tailnet-ssh-user"><Terminal size={14} />SSH 连接</label> | |
| 132 | 新增: <p className="field-help">填写这台设备的系统用户名。目标设备需开启 SSH,并允许当前账号登录。</p> | |
| 133 | 新增: <div className="tailscale-connect-form"><input id="tailnet-ssh-user" value={username} onChange={e => setUsername(e.target.value)} placeholder="设备的系统用户名" autoComplete="off" maxLength={128} /><button className="quiet-button" disabled={!username.trim() || !/^[a-zA-Z0-9_.@\\-]+$/.test(username.trim())} onClick={() => copy(`ssh -l '${username.trim()}' ${peer.ip}`, "已复制 SSH 命令,请在 Cage 终端运行")}>复制 SSH 命令</button></div> | |
| 134 | 新增: <p className="field-help">SSH、SFTP 与使用 OpenSSH 的工具可直接使用以上私网地址。其他应用的接入方式见下方“应用访问私网”。</p> | |
| 135 | 新增: </div>} | |
| 136 | 新增: </article>)}</div>} | |
| 137 | 新增: </section> | |
| 138 | 新增: {connected && <section className="tailscale-section"> | |
| 139 | 新增: <button className="tailscale-disclosure" aria-expanded={sshOpen} aria-controls="tailnet-inbound-ssh" onClick={() => setSSHOpen(!sshOpen)}><span><KeyRound size={16} />从其他设备 SSH 到 Cage</span><ChevronDown size={16} /></button> | |
| 140 | 新增: {sshOpen && <div id="tailnet-inbound-ssh" className="tailscale-detail"> | |
| 141 | 新增: <p className="field-help">仅在需要远程终端、SFTP 或编辑器连接时配置。将连接设备的 SSH 公钥添加到这里,私钥保留在原设备。</p> | |
| 142 | 新增: {address && <div className="tailscale-command"><code>{`ssh ${state.user}@${address}`}</code><button className="icon-button" aria-label="复制连接 Cage 命令" onClick={() => copy(`ssh ${state.user}@${address}`)}><Copy size={15} /></button></div>} | |
| 143 | 新增: <label className="field-label" htmlFor="tailscale-key">连接设备的 SSH 公钥</label> | |
| 144 | 新增: <textarea id="tailscale-key" rows={3} placeholder="ssh-ed25519 AAAA…" value={key} onChange={e => setKey(e.target.value)} maxLength={8192} spellCheck={false} /> | |
| 145 | 新增: <button className="quiet-button" disabled={busy || !key.trim()} onClick={() => act("add-key", { key: key.trim() })}>添加公钥</button> | |
| 146 | 新增: <div className="tailscale-keys">{(state.keys || []).map(entry => <div className="tailscale-key" key={entry}><code title={entry}>{entry}</code><button className="icon-button" disabled={busy} aria-label="移除 SSH 公钥" onClick={() => act("remove-key", { key: entry })}><Trash2 size={14} /></button></div>)}</div> | |
| 147 | 新增: </div>} | |
| 148 | 新增: </section>} | |
| 149 | 新增: {connected && state.proxy_url && <section className="tailscale-section"> | |
| 150 | 新增: <button className="tailscale-disclosure" aria-expanded={appsOpen} aria-controls="tailnet-apps" onClick={() => setAppsOpen(!appsOpen)}><span><Network size={16} />应用访问私网</span><ChevronDown size={16} /></button> | |
| 151 | 新增: {appsOpen && <div id="tailnet-apps" className="tailscale-detail"><p className="field-help">需要直接使用设备域名、HTTPS 或多个端口时,在 Cage 内的应用中配置 HTTP 代理。仅允许访问此私网中可见的设备,公网继续使用原有出口。</p><button className="quiet-button" onClick={() => copy(state.proxy_url, "已复制私网 HTTP 代理地址(含本地访问凭据)")}>复制私网代理地址</button><p className="field-help">代理地址含本地访问凭据,请仅用于 Cage 内的应用。此接入方式支持 TCP 服务;UDP、系统 VPN 和子网路由未启用。</p></div>} | |
| 152 | 新增: </section>} | |
| 153 | 新增: <p className="field-help tailscale-footer">其他设备需安装 Tailscale 并加入同一网络。设备访问受网络权限控制;暂停 Cage 联网或停止环境会中断私网连接。</p> | |
| 154 | 新增: {notice && <p className="tailscale-notice" role="status"><Check size={14} />{notice}</p>} | |
| 92 | 155 | </div> |
| 93 | 156 | </Modal>; |
| 94 | 157 | } |

