提交记录新增cmd/cage-mobile-link/README.md+111 −0看文件
新增cmd/cage-mobile-link/keepawake.go+22 −0看文件
新增cmd/cage-mobile-link/main.go+294 −0看文件
新增cmd/cage-mobile-link/profile_relay_test.go+34 −0看文件
新增cmd/cage-mobile-link/saved.go+274 −0看文件
新增cmd/cage-mobile-link/state.go+112 −0看文件
新增cmd/cage-mobile-link/workbench_test.go+288 −0看文件
新增cmd/cage-relay/main.go+149 −0看文件
新增cmd/cage-relay/main_test.go+158 −0看文件
新增deploy/relay/Caddyfile+22 −0看文件
新增deploy/relay/Dockerfile+15 −0看文件
新增deploy/relay/README.md+96 −0看文件
新增deploy/relay/compose.yaml+66 −0看文件
新增internal/mobilelink/backend.go+118 −0看文件
新增internal/mobilelink/browser.go+150 −0看文件
新增internal/mobilelink/device.go+38 −0看文件
新增internal/mobilelink/device_test.go+31 −0看文件
新增internal/mobilelink/link.go+277 −0看文件
新增internal/mobilelink/link_test.go+535 −0看文件
新增internal/mobilelink/nativeclient/client.go+269 −0看文件
新增internal/mobilelink/operations.go+206 −0看文件
新增internal/mobilelink/operations_test.go+75 −0看文件
新增internal/mobilelink/pair.go+137 −0看文件
新增internal/mobilelink/pair_test.go+79 −0看文件
新增internal/relay/server.go+393 −0看文件
新增internal/relay/server_test.go+345 −0看文件
新增internal/relay/tunnel_test.go+75 −0看文件
新增internal/remotelink/link.go+229 −0看文件
新增internal/remotelink/link_test.go+315 −0看文件
新增internal/remotelink/websocket.go+153 −0看文件
| @@ -0,0 +1,111 @@ | ||
| 1 | 新增:# 通过中继连接移动 CLI 会话 | |
| 2 | 新增: | |
| 3 | 新增:`cage-mobile-link` 把一个已信任设备连接到一台正在运行的 Cage 主机。客户端可以浏览主机授权的项目、创建 Claude Code 会话、发送消息、查看进度、回答工具审批和停止本轮执行。主机账户锁定时,这些操作返回 HTTP 423,需要在电脑上解锁。服务端继续负责项目授权、消息去重和执行结果。 | |
| 4 | 新增: | |
| 5 | 新增:使用官方中继时,按[手机使用说明](../../mobile/README.md)直接创建配对;主机助手默认读取桌面的中继设置。以下示例演示使用管理令牌的[自建中继](../../deploy/relay/README.md)。在电脑上启动包含移动 CLI 接口的 Cage,并构建主机连接助手。Android 和 iPhone 通过 [Cage 手机客户端](../../mobile/README.md)连接。若用另一台电脑的浏览器代替手机进行调试,该电脑也需构建本工具,并准备包含 `mobile.html` 和 `assets/` 的移动页面目录。 | |
| 6 | 新增: | |
| 7 | 新增:```sh | |
| 8 | 新增:go build -o /tmp/cage-mobile-link ./cmd/cage-mobile-link | |
| 9 | 新增:``` | |
| 10 | 新增: | |
| 11 | 新增:## 首次登记对端公钥 | |
| 12 | 新增: | |
| 13 | 新增:在电脑上执行一次初始化命令。为 `--state` 选择一个全新的专用目录,其父目录需要已存在。终端输出的 `sha256:…` 是电脑的公钥指纹,手机的公钥指纹在 App 首页。如果两端都使用命令行,则分别初始化。 | |
| 14 | 新增: | |
| 15 | 新增:```sh | |
| 16 | 新增:/tmp/cage-mobile-link init --state /path/to/new-device-state | |
| 17 | 新增:/tmp/cage-mobile-link fingerprint --state /path/to/new-device-state | |
| 18 | 新增:``` | |
| 19 | 新增: | |
| 20 | 新增:在两台设备旁核对指纹,或使用已经验证身份的独立通信渠道。核对后,把对方的完整公开指纹写入自己设备的信任记录。 | |
| 21 | 新增: | |
| 22 | 新增:```sh | |
| 23 | 新增:/tmp/cage-mobile-link trust \ | |
| 24 | 新增: --state /path/to/new-device-state \ | |
| 25 | 新增: --peer-pin 'sha256:对方实际的完整公开指纹' | |
| 26 | 新增:``` | |
| 27 | 新增: | |
| 28 | 新增:每个 CLI 状态目录只登记一个对端。首次登记依赖操作者核对指纹,信任记录拒绝覆盖。中继提供的房间身份只用于此次连接。CLI 设备身份由私有文件保存,macOS/Linux 使用用户权限,Windows 使用用户 ACL。每次连接用同一设备密钥签发短期证书,公钥指纹保持稳定。 | |
| 29 | 新增: | |
| 30 | 新增:## 在手机上保存主机 | |
| 31 | 新增: | |
| 32 | 新增:主机已登记手机指纹后,在电脑运行以下命令。管理令牌、Cage 程序与目标主机配置都使用绝对路径,方便以后从不同工作目录启动。 | |
| 33 | 新增: | |
| 34 | 新增:```sh | |
| 35 | 新增:/tmp/cage-mobile-link host \ | |
| 36 | 新增: --state /path/to/host-device-state \ | |
| 37 | 新增: --relay https://relay.example.com \ | |
| 38 | 新增: --admin-token-file /private/path/relay-admin-token \ | |
| 39 | 新增: --cage-bin /absolute/path/to/cage \ | |
| 40 | 新增: --config /absolute/path/to/config.json \ | |
| 41 | 新增: --connection-out /private/path/new-phone-connection.json | |
| 42 | 新增:``` | |
| 43 | 新增: | |
| 44 | 新增:将导出的连接文件私下传到手机并导入,在手机上逐字核对电脑独立显示的指纹,再保存主机。连接文件包含中继地址、版本号、主机公开指纹和这台手机专用的查找令牌。持有令牌可向中继索取当前房间的客户端接入资格,因此应保护连接文件。进入工作台还需要手机自己的设备私钥,主机也会向手机证明自己的身份。 | |
| 45 | 新增: | |
| 46 | 新增:此主机命令在运行期间持续维护一个可加入的房间。手机断开、房间过期或中继重启后,主机以同一查找凭据登记新房间。手机选择已保存主机即可重新连接,再从主机读取原会话。发送消息、审批和停止执行各自保留独立的请求语义,连接恢复只重建通信。主机进程重新启动时可直接读取该设备的私有配置。 | |
| 47 | 新增: | |
| 48 | 新增:```sh | |
| 49 | 新增:/tmp/cage-mobile-link host --state /path/to/host-device-state --serve-saved | |
| 50 | 新增:``` | |
| 51 | 新增: | |
| 52 | 新增:要撤销这台手机,在电脑对其专用状态目录执行以下命令。命令移除对端指纹和已保存的查找令牌,正在运行的桥接进程会在约一秒内关闭现有连接。主机设备密钥保留。重新授权时先登记经过核对的手机指纹,再生成新的连接文件;新文件使用新的随机查找令牌。 | |
| 53 | 新增: | |
| 54 | 新增:```sh | |
| 55 | 新增:/tmp/cage-mobile-link revoke --state /path/to/host-device-state | |
| 56 | 新增:``` | |
| 57 | 新增: | |
| 58 | 新增:每个状态目录对应一台获授权的手机。`--connection-out` 选择新的输出文件名;同一配置的重复导出沿用现有配对。替换已保存的中继、主机配置或手机身份前需要撤销并重新登记。 | |
| 59 | 新增: | |
| 60 | 新增:## 单次连接邀请 | |
| 61 | 新增: | |
| 62 | 新增:主机需要中继的管理令牌文件、可信 Cage 程序的绝对路径,以及目标主机配置的绝对路径。在主机执行以下命令,并保持进程运行。 | |
| 63 | 新增: | |
| 64 | 新增:```sh | |
| 65 | 新增:/tmp/cage-mobile-link host \ | |
| 66 | 新增: --state /path/to/host-device-state \ | |
| 67 | 新增: --relay https://relay.example.com \ | |
| 68 | 新增: --admin-token-file /private/path/relay-admin-token \ | |
| 69 | 新增: --cage-bin /absolute/path/to/cage \ | |
| 70 | 新增: --config /absolute/path/to/config.json \ | |
| 71 | 新增: --invitation-out /private/path/new-client-invitation.json | |
| 72 | 新增:``` | |
| 73 | 新增: | |
| 74 | 新增:将新生成的邀请文件通过私有渠道传给客户端,保留仅本人可读的权限。文件包含短期房间编号、客户端的一次性接入令牌和到期时间。中继域名与主机公钥指纹分别来自设备本地配置。主机通过本机 `server-entry --json` 取得票据并就地换取会话 Cookie,这两项凭据只在主机侧使用。 | |
| 75 | 新增: | |
| 76 | 新增:## 在客户端打开页面 | |
| 77 | 新增: | |
| 78 | 新增:在客户端设备启动本机桥接服务。将 `--web-dir` 指向可信的移动页面构建目录,为 `--launch-file` 选择一个新的私有 HTML 文件名。 | |
| 79 | 新增: | |
| 80 | 新增:```sh | |
| 81 | 新增:/tmp/cage-mobile-link client \ | |
| 82 | 新增: --state /path/to/client-device-state \ | |
| 83 | 新增: --relay https://relay.example.com \ | |
| 84 | 新增: --invitation-file /private/path/client-invitation.json \ | |
| 85 | 新增: --web-dir /absolute/path/to/mobile-build \ | |
| 86 | 新增: --launch-file /private/path/new-cage-entry.html | |
| 87 | 新增:``` | |
| 88 | 新增: | |
| 89 | 新增:在同一设备的浏览器中打开启动文件。入口在两分钟内可用一次,随即换成本机 HttpOnly 会话 Cookie。页面从本机回环地址加载,设备私钥、房间令牌和主机 Cookie 均由桥接进程管理。CLI 输出只提示下一步操作,避免将敏感入口打印到终端。 | |
| 90 | 新增: | |
| 91 | 新增:使用单次邀请时,断开后重新运行 `host` 创建新的短期邀请,再运行 `client`。使用已保存主机时,将 `--invitation-file` 换为 `--connection-file` 并传入保存的连接文件;中继地址和已核对的主机指纹必须与文件一致。两条命令的私有输出文件都拒绝覆盖,请使用新文件名。 | |
| 92 | 新增: | |
| 93 | 新增:## 原生 App 接入 | |
| 94 | 新增: | |
| 95 | 新增:[nativeclient](../../internal/mobilelink/nativeclient/client.go) 提供可绑定到 Swift 与 Android 的接口。平台保存 P-256 密钥,并向 Go 层提供公钥及 SHA-256 摘要签名能力。签名结果采用 X9.62 DER 编码。原生层可展示 `Fingerprint` 供主机核对,把经独立核对的主机指纹保存在设备信任记录中。 | |
| 96 | 新增: | |
| 97 | 新增:取得短期邀请后调用 `Open`,传入独立配置的中继地址、房间编号、客户端令牌、已信任的主机指纹和设备签名器。连接成功后,`StartUI` 接受应用自带资源的绝对目录,返回本机一次性启动 URL。原生 WebView 应只允许这次入口的精确源,并直接加载该 URL。原生界面也可调用 `Request`,接收 HTTP 状态、内容类型和响应体。退出该主机时调用 `Close`,释放本机页面服务、连接及运行中的读取。 | |
| 98 | 新增: | |
| 99 | 新增:保存主机时,原生层将查找令牌存入系统安全存储,同时单独保存已经核对的主机身份和中继地址。后续调用 `OpenSaved` 即可查找新房间并建立连接,参数依次为中继地址、查找令牌、已核对的主机指纹和设备签名器。该接口仅在读取目录时对短暂的房间交接等待进行有限重试。首次授权仍需独立核对指纹。移动页面与原生壳的构建说明见[移动工作台设计](../../docs/design/mobile-remote.md)。 | |
| 100 | 新增: | |
| 101 | 新增:## 验证真实工作台连接 | |
| 102 | 新增: | |
| 103 | 新增:下面的测试会新建临时 Cage 配置、本机账户和双方设备身份。它通过真实中继、端到端 TLS、主机票据交换与移动 API 验证项目读取、会话创建、按版本恢复、锁定和越权拒绝,还会验证保存主机后的房间重建、中继重启、主机桥重启以及撤销设备。测试不启动虚拟机或调用模型。 | |
| 104 | 新增: | |
| 105 | 新增:```sh | |
| 106 | 新增:go build -o /tmp/cage-mobile-e2e-backend ./cmd/cage | |
| 107 | 新增:CAGE_MOBILE_E2E_BINARY=/tmp/cage-mobile-e2e-backend \ | |
| 108 | 新增: go test -race -run TestIsolatedWorkbench ./cmd/cage-mobile-link | |
| 109 | 新增:``` | |
| 110 | 新增: | |
| 111 | 新增:如需验证人工传递邀请的等待时间,同时设置 `CAGE_MOBILE_E2E_DELAY_JOIN=1`。测试让客户端延后 16 秒进入房间,覆盖了用户加入用时超过单次 TLS 握手期限的场景。 | |
| @@ -0,0 +1,22 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "log" | |
| 6 | 新增: | |
| 7 | 新增: "github.com/sylvinus/agent-vm/internal/keepawake" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func keepHostAwake(parent context.Context, logger *log.Logger) func() { | |
| 11 | 新增: ctx, cancel := context.WithCancel(parent) | |
| 12 | 新增: done := make(chan struct{}) | |
| 13 | 新增: go func() { | |
| 14 | 新增: defer close(done) | |
| 15 | 新增: keepawake.Run(ctx, func(state keepawake.State) { | |
| 16 | 新增: if state.Error != "" { | |
| 17 | 新增: logger.Println("Host keep-awake unavailable:", state.Error) | |
| 18 | 新增: } | |
| 19 | 新增: }) | |
| 20 | 新增: }() | |
| 21 | 新增: return func() { cancel(); <-done } | |
| 22 | 新增:} | |
| @@ -0,0 +1,294 @@ | ||
| 1 | 新增:// cage-mobile-link provides a host bridge and an on-device browser client for | |
| 2 | 新增:// testing pre-provisioned mobile links. CLI state is explicitly selected. | |
| 3 | 新增:package main | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bytes" | |
| 7 | 新增: "context" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "errors" | |
| 10 | 新增: "flag" | |
| 11 | 新增: "fmt" | |
| 12 | 新增: "html" | |
| 13 | 新增: "io" | |
| 14 | 新增: "log" | |
| 15 | 新增: "net" | |
| 16 | 新增: "net/http" | |
| 17 | 新增: "os" | |
| 18 | 新增: "os/exec" | |
| 19 | 新增: "os/signal" | |
| 20 | 新增: "path/filepath" | |
| 21 | 新增: "strings" | |
| 22 | 新增: "syscall" | |
| 23 | 新增: "time" | |
| 24 | 新增: | |
| 25 | 新增: "github.com/sylvinus/agent-vm/internal/mobilelink" | |
| 26 | 新增:) | |
| 27 | 新增: | |
| 28 | 新增:const usage = `cage-mobile-link init --state NEW_DIRECTORY | |
| 29 | 新增:cage-mobile-link fingerprint --state DIRECTORY | |
| 30 | 新增:cage-mobile-link trust --state DIRECTORY --peer-pin VERIFIED_PUBLIC_FINGERPRINT | |
| 31 | 新增:cage-mobile-link revoke --state DIRECTORY | |
| 32 | 新增:cage-mobile-link host --state DIRECTORY [--relay HTTPS_ORIGIN] [--admin-token-file FILE] --invitation-out NEW_FILE --cage-bin ABSOLUTE_BINARY --config ABSOLUTE_CONFIG | |
| 33 | 新增:cage-mobile-link host --state DIRECTORY [--relay HTTPS_ORIGIN] [--admin-token-file ABSOLUTE_FILE] --connection-out NEW_FILE --cage-bin ABSOLUTE_BINARY --config ABSOLUTE_CONFIG | |
| 34 | 新增:cage-mobile-link host --state DIRECTORY --serve-saved | |
| 35 | 新增:cage-mobile-link client --state DIRECTORY [--relay HTTPS_ORIGIN] --invitation-file FILE --web-dir BUILD_DIRECTORY --launch-file NEW_HTML_FILE [--listen 127.0.0.1:0] | |
| 36 | 新增:cage-mobile-link client --state DIRECTORY [--relay HTTPS_ORIGIN] --connection-file FILE --web-dir BUILD_DIRECTORY --launch-file NEW_HTML_FILE [--listen 127.0.0.1:0] | |
| 37 | 新增:` | |
| 38 | 新增: | |
| 39 | 新增:func main() { | |
| 40 | 新增: ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) | |
| 41 | 新增: defer stop() | |
| 42 | 新增: if err := run(ctx, os.Args[1:], os.Stdout, os.Stderr); err != nil && !errors.Is(err, flag.ErrHelp) && !errors.Is(err, context.Canceled) { | |
| 43 | 新增: fmt.Fprintln(os.Stderr, "cage-mobile-link:", err) | |
| 44 | 新增: os.Exit(1) | |
| 45 | 新增: } | |
| 46 | 新增:} | |
| 47 | 新增: | |
| 48 | 新增:// New pairings use the desktop preference. Existing pairings retain the | |
| 49 | 新增:// origin to which their lookup and device credentials were issued. | |
| 50 | 新增:func profileRelay(config string) (string, error) { | |
| 51 | 新增: var prefs struct { | |
| 52 | 新增: MobileRelay string `json:"mobile_relay"` | |
| 53 | 新增: } | |
| 54 | 新增: b, err := os.ReadFile(filepath.Join(filepath.Dir(config), "workbench.json")) | |
| 55 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 56 | 新增: return mobilelink.OfficialRelay, nil | |
| 57 | 新增: } | |
| 58 | 新增: if err != nil { | |
| 59 | 新增: return "", err | |
| 60 | 新增: } | |
| 61 | 新增: if err := json.Unmarshal(b, &prefs); err != nil { | |
| 62 | 新增: return "", err | |
| 63 | 新增: } | |
| 64 | 新增: if prefs.MobileRelay == "" { | |
| 65 | 新增: return mobilelink.OfficialRelay, nil | |
| 66 | 新增: } | |
| 67 | 新增: if !strings.HasPrefix(prefs.MobileRelay, "https://") || !mobilelink.ValidRelayOrigin(prefs.MobileRelay) { | |
| 68 | 新增: return "", errors.New("invalid mobile relay in Cage settings") | |
| 69 | 新增: } | |
| 70 | 新增: return prefs.MobileRelay, nil | |
| 71 | 新增:} | |
| 72 | 新增: | |
| 73 | 新增:type clientInvitation struct { | |
| 74 | 新增: ID string `json:"id"` | |
| 75 | 新增: Token string `json:"client_token"` | |
| 76 | 新增: ExpiresAt time.Time `json:"expires_at"` | |
| 77 | 新增:} | |
| 78 | 新增: | |
| 79 | 新增:func run(ctx context.Context, args []string, out, errs io.Writer) error { | |
| 80 | 新增: if len(args) == 0 || args[0] == "--help" || args[0] == "help" { | |
| 81 | 新增: _, _ = io.WriteString(out, usage) | |
| 82 | 新增: return nil | |
| 83 | 新增: } | |
| 84 | 新增: cmd := args[0] | |
| 85 | 新增: f := flag.NewFlagSet("cage-mobile-link "+cmd, flag.ContinueOnError) | |
| 86 | 新增: f.SetOutput(errs) | |
| 87 | 新增: var state, pin, base, adminFile, invitation, connectionFile, cageBinary, config, webDir, launchFile, address string | |
| 88 | 新增: var serveSaved bool | |
| 89 | 新增: f.StringVar(&state, "state", "", "private device state directory") | |
| 90 | 新增: switch cmd { | |
| 91 | 新增: case "init", "fingerprint", "revoke": | |
| 92 | 新增: case "trust": | |
| 93 | 新增: f.StringVar(&pin, "peer-pin", "", "peer fingerprint verified through a trusted channel") | |
| 94 | 新增: case "host": | |
| 95 | 新增: f.StringVar(&base, "relay", "", "trusted relay HTTPS origin") | |
| 96 | 新增: f.StringVar(&adminFile, "admin-token-file", "", "private relay admin token file") | |
| 97 | 新增: f.StringVar(&invitation, "invitation-out", "", "new private file for client room credentials") | |
| 98 | 新增: f.StringVar(&connectionFile, "connection-out", "", "new private file for the paired phone to save") | |
| 99 | 新增: f.BoolVar(&serveSaved, "serve-saved", false, "keep serving the existing saved device pairing") | |
| 100 | 新增: f.StringVar(&cageBinary, "cage-bin", "", "absolute path to trusted cage binary") | |
| 101 | 新增: f.StringVar(&config, "config", "", "absolute path to the running Cage profile configuration") | |
| 102 | 新增: case "client": | |
| 103 | 新增: f.StringVar(&base, "relay", mobilelink.OfficialRelay, "trusted relay HTTPS origin") | |
| 104 | 新增: f.StringVar(&invitation, "invitation-file", "", "private invitation supplied by the host") | |
| 105 | 新增: f.StringVar(&connectionFile, "connection-file", "", "private saved connection file verified on this device") | |
| 106 | 新增: f.StringVar(&webDir, "web-dir", "", "trusted build directory containing mobile.html") | |
| 107 | 新增: f.StringVar(&launchFile, "launch-file", "", "new private local HTML entry file") | |
| 108 | 新增: f.StringVar(&address, "listen", "127.0.0.1:0", "local numeric loopback UI listener") | |
| 109 | 新增: default: | |
| 110 | 新增: return errors.New("unknown command; use --help") | |
| 111 | 新增: } | |
| 112 | 新增: if err := f.Parse(args[1:]); err != nil { | |
| 113 | 新增: return err | |
| 114 | 新增: } | |
| 115 | 新增: if state == "" || f.NArg() != 0 { | |
| 116 | 新增: return errors.New("--state is required; positional arguments are not supported") | |
| 117 | 新增: } | |
| 118 | 新增: if cmd == "init" { | |
| 119 | 新增: id, err := createIdentity(state) | |
| 120 | 新增: if err == nil { | |
| 121 | 新增: fmt.Fprintln(out, id.Pin) | |
| 122 | 新增: } | |
| 123 | 新增: return err | |
| 124 | 新增: } | |
| 125 | 新增: if cmd == "trust" { | |
| 126 | 新增: return trust(state, pin) | |
| 127 | 新增: } | |
| 128 | 新增: if cmd == "revoke" { | |
| 129 | 新增: return revoke(state) | |
| 130 | 新增: } | |
| 131 | 新增: id, err := loadIdentity(state) | |
| 132 | 新增: if err != nil { | |
| 133 | 新增: return err | |
| 134 | 新增: } | |
| 135 | 新增: if cmd == "fingerprint" { | |
| 136 | 新增: fmt.Fprintln(out, id.Pin) | |
| 137 | 新增: return nil | |
| 138 | 新增: } | |
| 139 | 新增: peer, err := trustedPeer(state) | |
| 140 | 新增: if err != nil { | |
| 141 | 新增: return err | |
| 142 | 新增: } | |
| 143 | 新增: if cmd == "host" { | |
| 144 | 新增: if serveSaved { | |
| 145 | 新增: if base != "" || adminFile != "" || invitation != "" || connectionFile != "" || cageBinary != "" || config != "" { | |
| 146 | 新增: return errors.New("--serve-saved uses only the configuration saved for --state") | |
| 147 | 新增: } | |
| 148 | 新增: h, err := loadSavedHost(state, id.Pin, peer) | |
| 149 | 新增: if err != nil { | |
| 150 | 新增: return err | |
| 151 | 新增: } | |
| 152 | 新增: return savedService(ctx, state, h, errs) | |
| 153 | 新增: } | |
| 154 | 新增: if base == "" { | |
| 155 | 新增: if adminFile != "" { | |
| 156 | 新增: return errors.New("specify --relay together with --admin-token-file to confirm the destination of the private token") | |
| 157 | 新增: } | |
| 158 | 新增: if !filepath.IsAbs(config) { | |
| 159 | 新增: return errors.New("host requires an absolute --config") | |
| 160 | 新增: } | |
| 161 | 新增: base, err = profileRelay(config) | |
| 162 | 新增: if err != nil { | |
| 163 | 新增: return err | |
| 164 | 新增: } | |
| 165 | 新增: } | |
| 166 | 新增: if connectionFile != "" { | |
| 167 | 新增: if invitation != "" { | |
| 168 | 新增: return errors.New("choose --connection-out or --invitation-out") | |
| 169 | 新增: } | |
| 170 | 新增: h, err := configureSavedHost(state, connectionFile, id.Pin, peer, hostSettings{Relay: base, AdminFile: adminFile, CageBinary: cageBinary, Config: config}) | |
| 171 | 新增: if err != nil { | |
| 172 | 新增: return err | |
| 173 | 新增: } | |
| 174 | 新增: fmt.Fprintln(out, "Private saved connection file written. Verify the host fingerprint separately on the phone.") | |
| 175 | 新增: return savedService(ctx, state, h, errs) | |
| 176 | 新增: } | |
| 177 | 新增: if !filepath.IsAbs(cageBinary) || !filepath.IsAbs(config) || invitation == "" { | |
| 178 | 新增: return errors.New("host requires absolute --cage-bin, --config, and a new --invitation-out file") | |
| 179 | 新增: } | |
| 180 | 新增: b, err := localWorkbench(ctx, cageBinary, config) | |
| 181 | 新增: if err != nil { | |
| 182 | 新增: return err | |
| 183 | 新增: } | |
| 184 | 新增: defer b.Close() | |
| 185 | 新增: admin, err := readAdminToken(adminFile) | |
| 186 | 新增: if err != nil { | |
| 187 | 新增: return err | |
| 188 | 新增: } | |
| 189 | 新增: room, err := mobilelink.CreateRoom(ctx, base, admin) | |
| 190 | 新增: if err != nil { | |
| 191 | 新增: return err | |
| 192 | 新增: } | |
| 193 | 新增: data, _ := json.Marshal(clientInvitation{room.ID, room.ClientToken, room.ExpiresAt}) | |
| 194 | 新增: err = writeNewPrivate(invitation, data) | |
| 195 | 新增: clear(data) | |
| 196 | 新增: if err != nil { | |
| 197 | 新增: return err | |
| 198 | 新增: } | |
| 199 | 新增: fmt.Fprintln(out, "Private client invitation saved. Waiting for the trusted device.") | |
| 200 | 新增: active, stop := monitorTrust(ctx, func() bool { current, err := trustedPeer(state); return err == nil && current == peer }) | |
| 201 | 新增: defer stop() | |
| 202 | 新增: stopAwake := keepHostAwake(active, log.New(errs, "", 0)) | |
| 203 | 新增: defer stopAwake() | |
| 204 | 新增: err = mobilelink.ServeHost(active, base, room.ID, room.HostToken, id, peer, b) | |
| 205 | 新增: if active.Err() != nil { | |
| 206 | 新增: return context.Cause(active) | |
| 207 | 新增: } | |
| 208 | 新增: return err | |
| 209 | 新增: } | |
| 210 | 新增: if launchFile == "" || webDir == "" { | |
| 211 | 新增: return errors.New("client requires --web-dir and a new --launch-file") | |
| 212 | 新增: } | |
| 213 | 新增: var room clientInvitation | |
| 214 | 新增: if connectionFile != "" { | |
| 215 | 新增: if invitation != "" { | |
| 216 | 新增: return errors.New("choose --connection-file or --invitation-file") | |
| 217 | 新增: } | |
| 218 | 新增: room, err = resolveSaved(ctx, connectionFile, base, peer) | |
| 219 | 新增: if err != nil { | |
| 220 | 新增: return err | |
| 221 | 新增: } | |
| 222 | 新增: } else { | |
| 223 | 新增: data, err := readPrivate(invitation, 4096) | |
| 224 | 新增: if err != nil { | |
| 225 | 新增: return err | |
| 226 | 新增: } | |
| 227 | 新增: err = json.Unmarshal(data, &room) | |
| 228 | 新增: clear(data) | |
| 229 | 新增: if err != nil || !room.ExpiresAt.After(time.Now()) { | |
| 230 | 新增: return errors.New("invalid or expired client invitation") | |
| 231 | 新增: } | |
| 232 | 新增: } | |
| 233 | 新增: host, _, err := net.SplitHostPort(address) | |
| 234 | 新增: if err != nil || !net.ParseIP(host).IsLoopback() { | |
| 235 | 新增: return errors.New("the local browser must use a numeric loopback address") | |
| 236 | 新增: } | |
| 237 | 新增: listener, err := net.Listen("tcp", address) | |
| 238 | 新增: if err != nil { | |
| 239 | 新增: return errors.New("cannot listen on the requested loopback address") | |
| 240 | 新增: } | |
| 241 | 新增: defer listener.Close() | |
| 242 | 新增: client, err := mobilelink.ConnectClient(ctx, base, room.ID, room.Token, id, peer) | |
| 243 | 新增: if err != nil { | |
| 244 | 新增: return err | |
| 245 | 新增: } | |
| 246 | 新增: defer client.Close() | |
| 247 | 新增: browser, entry, err := mobilelink.NewBrowser("http://"+listener.Addr().String(), webDir, client) | |
| 248 | 新增: if err != nil { | |
| 249 | 新增: return err | |
| 250 | 新增: } | |
| 251 | 新增: defer browser.Close() | |
| 252 | 新增: page := []byte(`<!doctype html><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=` + html.EscapeString(entry) + `"><title>Cage</title>`) | |
| 253 | 新增: err = writeNewPrivate(launchFile, page) | |
| 254 | 新增: clear(page) | |
| 255 | 新增: if err != nil { | |
| 256 | 新增: return err | |
| 257 | 新增: } | |
| 258 | 新增: fmt.Fprintln(out, "Authenticated. Open the private HTML launch file on this device within two minutes.") | |
| 259 | 新增: server := &http.Server{Handler: browser, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 45 * time.Second, IdleTimeout: time.Minute, MaxHeaderBytes: 16 << 10, ErrorLog: log.New(io.Discard, "", 0)} | |
| 260 | 新增: stop := context.AfterFunc(ctx, func() { _ = server.Close() }) | |
| 261 | 新增: defer stop() | |
| 262 | 新增: err = server.Serve(listener) | |
| 263 | 新增: if errors.Is(err, http.ErrServerClosed) { | |
| 264 | 新增: return nil | |
| 265 | 新增: } | |
| 266 | 新增: return err | |
| 267 | 新增:} | |
| 268 | 新增: | |
| 269 | 新增:type entryBuffer struct{ buf bytes.Buffer } | |
| 270 | 新增: | |
| 271 | 新增:func (b *entryBuffer) Write(p []byte) (int, error) { | |
| 272 | 新增: if len(p) > (16<<10)-b.buf.Len() { | |
| 273 | 新增: return 0, errors.New("Cage entry too large") | |
| 274 | 新增: } | |
| 275 | 新增: return b.buf.Write(p) | |
| 276 | 新增:} | |
| 277 | 新增: | |
| 278 | 新增:func localWorkbench(ctx context.Context, cageBinary, config string) (*mobilelink.Workbench, error) { | |
| 279 | 新增: ctx, cancel := context.WithTimeout(ctx, 10*time.Second) | |
| 280 | 新增: defer cancel() | |
| 281 | 新增: cmd := exec.CommandContext(ctx, cageBinary, "server-entry", "--json") | |
| 282 | 新增: cmd.Env = append(os.Environ(), "CLAUDE_CAGE_CONFIG="+config) | |
| 283 | 新增: buf := &entryBuffer{} | |
| 284 | 新增: cmd.Stdout, cmd.Stderr = buf, io.Discard | |
| 285 | 新增: if err := cmd.Run(); err != nil { | |
| 286 | 新增: return nil, errors.New("Cage could not issue a local entry; start the selected profile first") | |
| 287 | 新增: } | |
| 288 | 新增: defer clear(buf.buf.Bytes()) | |
| 289 | 新增: var entry struct{ Origin, Ticket string } | |
| 290 | 新增: if json.Unmarshal(buf.buf.Bytes(), &entry) != nil { | |
| 291 | 新增: return nil, errors.New("Cage returned an invalid local entry") | |
| 292 | 新增: } | |
| 293 | 新增: return mobilelink.OpenWorkbench(ctx, entry.Origin, entry.Ticket) | |
| 294 | 新增:} | |
| @@ -0,0 +1,34 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "testing" | |
| 7 | 新增: | |
| 8 | 新增: "github.com/sylvinus/agent-vm/internal/mobilelink" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func TestNewPairingUsesDesktopRelay(t *testing.T) { | |
| 12 | 新增: dir := t.TempDir() | |
| 13 | 新增: config := filepath.Join(dir, "config.json") | |
| 14 | 新增: prefs := filepath.Join(dir, "workbench.json") | |
| 15 | 新增: for _, tc := range []struct{ name, json, want string }{ | |
| 16 | 新增: {"new profile", "", mobilelink.OfficialRelay}, | |
| 17 | 新增: {"existing profile", `{"keyboard":"mac"}`, mobilelink.OfficialRelay}, | |
| 18 | 新增: {"custom relay", `{"mobile_relay":"https://relay.example:8443"}`, "https://relay.example:8443"}, | |
| 19 | 新增: {"damaged preferences", "{", ""}, | |
| 20 | 新增: {"insecure relay", `{"mobile_relay":"http://relay.example"}`, ""}, | |
| 21 | 新增: } { | |
| 22 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 23 | 新增: if tc.json != "" { | |
| 24 | 新增: if err := os.WriteFile(prefs, []byte(tc.json), 0600); err != nil { | |
| 25 | 新增: t.Fatal(err) | |
| 26 | 新增: } | |
| 27 | 新增: } | |
| 28 | 新增: origin, err := profileRelay(config) | |
| 29 | 新增: if origin != tc.want || (err != nil) != (tc.want == "") { | |
| 30 | 新增: t.Fatalf("origin = %q, error = %v", origin, err) | |
| 31 | 新增: } | |
| 32 | 新增: }) | |
| 33 | 新增: } | |
| 34 | 新增:} | |
| @@ -0,0 +1,274 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/rand" | |
| 7 | 新增: "encoding/base64" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "errors" | |
| 10 | 新增: "io" | |
| 11 | 新增: "log" | |
| 12 | 新增: "os" | |
| 13 | 新增: "path/filepath" | |
| 14 | 新增: "runtime" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "time" | |
| 17 | 新增: | |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/mobilelink" | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 21 | 新增:// connectionFile is the only long-lived record exported to the phone. | |
| 22 | 新增:// Its token may claim a transport role, but cannot authenticate either peer. | |
| 23 | 新增:type connectionFile struct { | |
| 24 | 新增: Version int `json:"version"` | |
| 25 | 新增: Relay string `json:"relay"` | |
| 26 | 新增: LookupToken string `json:"lookup_token"` | |
| 27 | 新增: HostPin string `json:"host_pin"` | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:type hostSettings struct { | |
| 31 | 新增: Relay string `json:"relay"` | |
| 32 | 新增: AdminFile string `json:"admin_token_file"` | |
| 33 | 新增: CageBinary string `json:"cage_binary"` | |
| 34 | 新增: Config string `json:"config"` | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:type savedHost struct { | |
| 38 | 新增: Connection connectionFile `json:"connection"` | |
| 39 | 新增: Settings hostSettings `json:"host"` | |
| 40 | 新增: PeerPin string `json:"peer_pin"` | |
| 41 | 新增:} | |
| 42 | 新增: | |
| 43 | 新增:func decodePrivateJSON(path string, result any) error { | |
| 44 | 新增: data, err := readPrivate(path, 16<<10) | |
| 45 | 新增: if err != nil { | |
| 46 | 新增: return err | |
| 47 | 新增: } | |
| 48 | 新增: defer clear(data) | |
| 49 | 新增: decoder := json.NewDecoder(bytes.NewReader(data)) | |
| 50 | 新增: decoder.DisallowUnknownFields() | |
| 51 | 新增: if decoder.Decode(result) != nil || decoder.Decode(new(any)) != io.EOF { | |
| 52 | 新增: return errors.New("invalid private connection record") | |
| 53 | 新增: } | |
| 54 | 新增: return nil | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:func (c connectionFile) valid() bool { | |
| 58 | 新增: raw, err := base64.RawURLEncoding.DecodeString(c.LookupToken) | |
| 59 | 新增: defer clear(raw) | |
| 60 | 新增: return c.Version == 1 && mobilelink.ValidRelayOrigin(c.Relay) && validPin(c.HostPin) && err == nil && len(raw) == 32 && base64.RawURLEncoding.EncodeToString(raw) == c.LookupToken | |
| 61 | 新增:} | |
| 62 | 新增: | |
| 63 | 新增:func (s hostSettings) valid() bool { | |
| 64 | 新增: return mobilelink.ValidRelayOrigin(s.Relay) && (s.AdminFile == "" || filepath.IsAbs(s.AdminFile)) && filepath.IsAbs(s.Config) && filepath.IsAbs(s.CageBinary) | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:func loadSavedHost(state, hostPin, peerPin string) (savedHost, error) { | |
| 68 | 新增: var h savedHost | |
| 69 | 新增: err := decodePrivateJSON(filepath.Join(state, "saved-host.json"), &h) | |
| 70 | 新增: if err != nil { | |
| 71 | 新增: return h, err | |
| 72 | 新增: } | |
| 73 | 新增: if !h.Connection.valid() || !h.Settings.valid() || h.Connection.Relay != h.Settings.Relay || h.Connection.HostPin != hostPin || h.PeerPin != peerPin { | |
| 74 | 新增: return savedHost{}, errors.New("saved host settings no longer match this pairing; verify the device state") | |
| 75 | 新增: } | |
| 76 | 新增: return h, nil | |
| 77 | 新增:} | |
| 78 | 新增: | |
| 79 | 新增:func configureSavedHost(state, dest, hostPin, peerPin string, settings hostSettings) (savedHost, error) { | |
| 80 | 新增: var h savedHost | |
| 81 | 新增: if !settings.valid() { | |
| 82 | 新增: return h, errors.New("saved host requires a trusted relay and absolute admin token, cage binary and config paths") | |
| 83 | 新增: } | |
| 84 | 新增: if info, err := os.Stat(settings.CageBinary); err != nil || !info.Mode().IsRegular() || (runtime.GOOS != "windows" && info.Mode().Perm()&0111 == 0) { | |
| 85 | 新增: return h, errors.New("saved Cage binary must be an executable file") | |
| 86 | 新增: } | |
| 87 | 新增: if _, err := readAdminToken(settings.AdminFile); err != nil { | |
| 88 | 新增: return h, err | |
| 89 | 新增: } | |
| 90 | 新增: path := filepath.Join(state, "saved-host.json") | |
| 91 | 新增: _, err := os.Lstat(path) | |
| 92 | 新增: switch { | |
| 93 | 新增: case err == nil: | |
| 94 | 新增: h, err = loadSavedHost(state, hostPin, peerPin) | |
| 95 | 新增: if err != nil { | |
| 96 | 新增: return h, err | |
| 97 | 新增: } | |
| 98 | 新增: if h.Settings != settings { | |
| 99 | 新增: return h, errors.New("existing saved host settings differ; revoke this pairing before replacing it") | |
| 100 | 新增: } | |
| 101 | 新增: case errors.Is(err, os.ErrNotExist): | |
| 102 | 新增: raw := make([]byte, 32) | |
| 103 | 新增: _, _ = rand.Read(raw) | |
| 104 | 新增: h = savedHost{Connection: connectionFile{Version: 1, Relay: settings.Relay, LookupToken: base64.RawURLEncoding.EncodeToString(raw), HostPin: hostPin}, Settings: settings, PeerPin: peerPin} | |
| 105 | 新增: clear(raw) | |
| 106 | 新增: data, _ := json.Marshal(h) | |
| 107 | 新增: err = writeNewPrivate(path, data) | |
| 108 | 新增: clear(data) | |
| 109 | 新增: if err != nil { | |
| 110 | 新增: return savedHost{}, err | |
| 111 | 新增: } | |
| 112 | 新增: default: | |
| 113 | 新增: return h, errors.New("cannot inspect saved host settings") | |
| 114 | 新增: } | |
| 115 | 新增: data, _ := json.Marshal(h.Connection) | |
| 116 | 新增: err = writeNewPrivate(dest, data) | |
| 117 | 新增: clear(data) | |
| 118 | 新增: return h, err | |
| 119 | 新增:} | |
| 120 | 新增: | |
| 121 | 新增:func readAdminToken(path string) (string, error) { | |
| 122 | 新增: if path == "" { | |
| 123 | 新增: return "", nil | |
| 124 | 新增: } | |
| 125 | 新增: raw, err := readPrivate(path, 4098) | |
| 126 | 新增: if err != nil { | |
| 127 | 新增: return "", err | |
| 128 | 新增: } | |
| 129 | 新增: defer clear(raw) | |
| 130 | 新增: token := string(raw) | |
| 131 | 新增: if strings.HasSuffix(token, "\n") { | |
| 132 | 新增: token = strings.TrimSuffix(strings.TrimSuffix(token, "\n"), "\r") | |
| 133 | 新增: } | |
| 134 | 新增: if len(token) < 32 || len(token) > 4096 { | |
| 135 | 新增: return "", errors.New("invalid protected relay admin token") | |
| 136 | 新增: } | |
| 137 | 新增: for i := range len(token) { | |
| 138 | 新增: if token[i] < 0x21 || token[i] > 0x7e { | |
| 139 | 新增: return "", errors.New("invalid protected relay admin token") | |
| 140 | 新增: } | |
| 141 | 新增: } | |
| 142 | 新增: return token, nil | |
| 143 | 新增:} | |
| 144 | 新增: | |
| 145 | 新增:func revoke(state string) error { | |
| 146 | 新增: if _, err := loadIdentity(state); err != nil { | |
| 147 | 新增: return err | |
| 148 | 新增: } | |
| 149 | 新增: // Remove peer trust first, so an active saved bridge refuses access even | |
| 150 | 新增: // if a filesystem error interrupts deletion of the lookup credential. | |
| 151 | 新增: for _, name := range []string{"trusted-peer", "saved-host.json"} { | |
| 152 | 新增: if err := os.Remove(filepath.Join(state, name)); err != nil && !errors.Is(err, os.ErrNotExist) { | |
| 153 | 新增: return errors.New("could not revoke saved device state") | |
| 154 | 新增: } | |
| 155 | 新增: } | |
| 156 | 新增: return nil | |
| 157 | 新增:} | |
| 158 | 新增: | |
| 159 | 新增:var errRevoked = errors.New("saved device trust changed; host bridge closed") | |
| 160 | 新增: | |
| 161 | 新增:func verifySaved(state string, h savedHost) bool { | |
| 162 | 新增: peer, err := trustedPeer(state) | |
| 163 | 新增: if err != nil || peer != h.PeerPin { | |
| 164 | 新增: return false | |
| 165 | 新增: } | |
| 166 | 新增: current, err := loadSavedHost(state, h.Connection.HostPin, peer) | |
| 167 | 新增: return err == nil && current == h | |
| 168 | 新增:} | |
| 169 | 新增: | |
| 170 | 新增:func monitorTrust(parent context.Context, verify func() bool) (context.Context, func()) { | |
| 171 | 新增: ctx, cancel := context.WithCancelCause(parent) | |
| 172 | 新增: // Blocked TLS handshakes and already connected clients must also notice | |
| 173 | 新增: // revocation. A removed/replaced private trust record closes this bridge. | |
| 174 | 新增: go func() { | |
| 175 | 新增: ticker := time.NewTicker(time.Second) | |
| 176 | 新增: defer ticker.Stop() | |
| 177 | 新增: for { | |
| 178 | 新增: select { | |
| 179 | 新增: case <-ctx.Done(): | |
| 180 | 新增: return | |
| 181 | 新增: case <-ticker.C: | |
| 182 | 新增: if !verify() { | |
| 183 | 新增: cancel(errRevoked) | |
| 184 | 新增: return | |
| 185 | 新增: } | |
| 186 | 新增: } | |
| 187 | 新增: } | |
| 188 | 新增: }() | |
| 189 | 新增: return ctx, func() { cancel(nil) } | |
| 190 | 新增:} | |
| 191 | 新增: | |
| 192 | 新增:func savedService(parent context.Context, state string, h savedHost, out io.Writer) error { | |
| 193 | 新增: ctx, stop := monitorTrust(parent, func() bool { return verifySaved(state, h) }) | |
| 194 | 新增: defer stop() | |
| 195 | 新增: logger := log.New(out, "", 0) | |
| 196 | 新增: stopAwake := keepHostAwake(ctx, logger) | |
| 197 | 新增: defer stopAwake() | |
| 198 | 新增: delay := time.Second | |
| 199 | 新增: for ctx.Err() == nil { | |
| 200 | 新增: if !verifySaved(state, h) { | |
| 201 | 新增: return errRevoked | |
| 202 | 新增: } | |
| 203 | 新增: retry, err := savedRoom(ctx, state, h) | |
| 204 | 新增: if ctx.Err() != nil { | |
| 205 | 新增: break | |
| 206 | 新增: } | |
| 207 | 新增: if !retry { | |
| 208 | 新增: return err | |
| 209 | 新增: } | |
| 210 | 新增: if err == nil { | |
| 211 | 新增: delay = time.Second | |
| 212 | 新增: } else { | |
| 213 | 新增: logger.Println("Room unavailable; retrying the saved connection in", delay.String()) | |
| 214 | 新增: } | |
| 215 | 新增: timer := time.NewTimer(delay) | |
| 216 | 新增: select { | |
| 217 | 新增: case <-ctx.Done(): | |
| 218 | 新增: timer.Stop() | |
| 219 | 新增: return context.Cause(ctx) | |
| 220 | 新增: case <-timer.C: | |
| 221 | 新增: } | |
| 222 | 新增: if err != nil { | |
| 223 | 新增: delay = min(30*time.Second, 2*delay) | |
| 224 | 新增: } | |
| 225 | 新增: } | |
| 226 | 新增: return context.Cause(ctx) | |
| 227 | 新增:} | |
| 228 | 新增: | |
| 229 | 新增:func savedRoom(ctx context.Context, state string, h savedHost) (bool, error) { | |
| 230 | 新增: // Issue a fresh short-lived certificate and local Cage session for each | |
| 231 | 新增: // room. This also handles a restarted desktop control service. | |
| 232 | 新增: id, err := loadIdentity(state) | |
| 233 | 新增: if err != nil || id.Pin != h.Connection.HostPin { | |
| 234 | 新增: return false, errors.New("device identity changed") | |
| 235 | 新增: } | |
| 236 | 新增: if info, err := os.Stat(h.Settings.CageBinary); err != nil || !info.Mode().IsRegular() { | |
| 237 | 新增: return false, errors.New("saved Cage binary unavailable") | |
| 238 | 新增: } | |
| 239 | 新增: admin, err := readAdminToken(h.Settings.AdminFile) | |
| 240 | 新增: if err != nil { | |
| 241 | 新增: return false, err | |
| 242 | 新增: } | |
| 243 | 新增: b, err := localWorkbench(ctx, h.Settings.CageBinary, h.Settings.Config) | |
| 244 | 新增: if err != nil { | |
| 245 | 新增: return true, err | |
| 246 | 新增: } | |
| 247 | 新增: defer b.Close() | |
| 248 | 新增: room, err := mobilelink.CreateDiscoverableRoom(ctx, h.Settings.Relay, admin, h.Connection.LookupToken) | |
| 249 | 新增: if err != nil { | |
| 250 | 新增: return mobilelink.Retryable(err), err | |
| 251 | 新增: } | |
| 252 | 新增: err = mobilelink.ServeHost(ctx, h.Settings.Relay, room.ID, room.HostToken, id, h.PeerPin, b) | |
| 253 | 新增: if mobilelink.Retryable(err) && !time.Now().Before(room.ExpiresAt) { | |
| 254 | 新增: // An unused room reaching its normal pairing deadline is healthy. | |
| 255 | 新增: // Publish the next room without accumulating offline backoff. | |
| 256 | 新增: return true, nil | |
| 257 | 新增: } | |
| 258 | 新增: return err == nil || mobilelink.Retryable(err), err | |
| 259 | 新增:} | |
| 260 | 新增: | |
| 261 | 新增:func resolveSaved(ctx context.Context, path, base, peer string) (clientInvitation, error) { | |
| 262 | 新增: var c connectionFile | |
| 263 | 新增: if err := decodePrivateJSON(path, &c); err != nil { | |
| 264 | 新增: return clientInvitation{}, err | |
| 265 | 新增: } | |
| 266 | 新增: if !c.valid() || c.Relay != base || c.HostPin != peer { | |
| 267 | 新增: return clientInvitation{}, errors.New("connection file differs from independently trusted host or relay") | |
| 268 | 新增: } | |
| 269 | 新增: found, err := mobilelink.LookupRoom(ctx, base, c.LookupToken) | |
| 270 | 新增: if err != nil { | |
| 271 | 新增: return clientInvitation{}, err | |
| 272 | 新增: } | |
| 273 | 新增: return clientInvitation{found.ID, found.ClientToken, found.ExpiresAt}, nil | |
| 274 | 新增:} | |
| @@ -0,0 +1,112 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "crypto/ed25519" | |
| 5 | 新增: "crypto/rand" | |
| 6 | 新增: "encoding/base64" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "io" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "strings" | |
| 12 | 新增: | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/remotelink" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:func writeNewPrivate(path string, data []byte) error { | |
| 18 | 新增: if path == "" { | |
| 19 | 新增: return errors.New("a private output file is required") | |
| 20 | 新增: } | |
| 21 | 新增: f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: return errors.New("cannot create private output; choose a new file") | |
| 24 | 新增: } | |
| 25 | 新增: if err = host.ProtectFile(path); err == nil { | |
| 26 | 新增: _, err = f.Write(data) | |
| 27 | 新增: } | |
| 28 | 新增: if err == nil { | |
| 29 | 新增: err = f.Sync() | |
| 30 | 新增: } | |
| 31 | 新增: closeErr := f.Close() | |
| 32 | 新增: if err != nil || closeErr != nil { | |
| 33 | 新增: _ = os.Remove(path) | |
| 34 | 新增: return errors.New("could not save private output") | |
| 35 | 新增: } | |
| 36 | 新增: return nil | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:func readPrivate(path string, limit int64) ([]byte, error) { | |
| 40 | 新增: if err := host.CheckPrivateFile(path); err != nil { | |
| 41 | 新增: return nil, errors.New("missing or insecure private file") | |
| 42 | 新增: } | |
| 43 | 新增: f, err := os.Open(path) | |
| 44 | 新增: if err != nil { | |
| 45 | 新增: return nil, errors.New("cannot open private file") | |
| 46 | 新增: } | |
| 47 | 新增: defer f.Close() | |
| 48 | 新增: data, err := io.ReadAll(io.LimitReader(f, limit+1)) | |
| 49 | 新增: if err != nil || int64(len(data)) > limit { | |
| 50 | 新增: clear(data) | |
| 51 | 新增: return nil, errors.New("private file exceeds limit or could not be read") | |
| 52 | 新增: } | |
| 53 | 新增: return data, nil | |
| 54 | 新增:} | |
| 55 | 新增: | |
| 56 | 新增:func createIdentity(dir string) (*remotelink.Identity, error) { | |
| 57 | 新增: // Require a new directory: do not change permissions on an existing home | |
| 58 | 新增: // or other user-supplied directory. | |
| 59 | 新增: if err := os.Mkdir(dir, 0700); err != nil { | |
| 60 | 新增: return nil, errors.New("identity initialization requires a new state directory in an existing parent") | |
| 61 | 新增: } | |
| 62 | 新增: if err := host.EnsurePrivateDir(dir); err != nil { | |
| 63 | 新增: return nil, err | |
| 64 | 新增: } | |
| 65 | 新增: seed := make([]byte, ed25519.SeedSize) | |
| 66 | 新增: _, _ = rand.Read(seed) | |
| 67 | 新增: defer clear(seed) | |
| 68 | 新增: if err := writeNewPrivate(filepath.Join(dir, "device.seed"), seed); err != nil { | |
| 69 | 新增: return nil, err | |
| 70 | 新增: } | |
| 71 | 新增: return remotelink.IdentityFromKey(ed25519.NewKeyFromSeed(seed)) | |
| 72 | 新增:} | |
| 73 | 新增: | |
| 74 | 新增:func loadIdentity(dir string) (*remotelink.Identity, error) { | |
| 75 | 新增: seed, err := readPrivate(filepath.Join(dir, "device.seed"), ed25519.SeedSize) | |
| 76 | 新增: if err != nil { | |
| 77 | 新增: return nil, err | |
| 78 | 新增: } | |
| 79 | 新增: defer clear(seed) | |
| 80 | 新增: if len(seed) != ed25519.SeedSize { | |
| 81 | 新增: return nil, errors.New("invalid device identity; preserve its state directory") | |
| 82 | 新增: } | |
| 83 | 新增: return remotelink.IdentityFromKey(ed25519.NewKeyFromSeed(seed)) | |
| 84 | 新增:} | |
| 85 | 新增: | |
| 86 | 新增:func validPin(value string) bool { | |
| 87 | 新增: s, ok := strings.CutPrefix(value, "sha256:") | |
| 88 | 新增: b, err := base64.StdEncoding.DecodeString(s) | |
| 89 | 新增: return ok && err == nil && len(b) == 32 && base64.StdEncoding.EncodeToString(b) == s | |
| 90 | 新增:} | |
| 91 | 新增: | |
| 92 | 新增:func trust(dir, pin string) error { | |
| 93 | 新增: if !validPin(pin) { | |
| 94 | 新增: return errors.New("invalid verified peer fingerprint") | |
| 95 | 新增: } | |
| 96 | 新增: identity, err := loadIdentity(dir) | |
| 97 | 新增: if err != nil { | |
| 98 | 新增: return err | |
| 99 | 新增: } | |
| 100 | 新增: if pin == identity.Pin { | |
| 101 | 新增: return errors.New("peer fingerprint must identify a different device") | |
| 102 | 新增: } | |
| 103 | 新增: return writeNewPrivate(filepath.Join(dir, "trusted-peer"), []byte(pin)) | |
| 104 | 新增:} | |
| 105 | 新增: | |
| 106 | 新增:func trustedPeer(dir string) (string, error) { | |
| 107 | 新增: b, err := readPrivate(filepath.Join(dir, "trusted-peer"), 256) | |
| 108 | 新增: if err != nil || !validPin(string(b)) { | |
| 109 | 新增: return "", errors.New("register an independently verified peer fingerprint first") | |
| 110 | 新增: } | |
| 111 | 新增: return string(b), nil | |
| 112 | 新增:} | |
| @@ -0,0 +1,288 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/rand" | |
| 7 | 新增: "encoding/hex" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "io" | |
| 10 | 新增: "net/http" | |
| 11 | 新增: "net/http/cookiejar" | |
| 12 | 新增: "net/http/httptest" | |
| 13 | 新增: "net/url" | |
| 14 | 新增: "os" | |
| 15 | 新增: "os/exec" | |
| 16 | 新增: "path/filepath" | |
| 17 | 新增: "regexp" | |
| 18 | 新增: "strings" | |
| 19 | 新增: "sync" | |
| 20 | 新增: "sync/atomic" | |
| 21 | 新增: "testing" | |
| 22 | 新增: "time" | |
| 23 | 新增: | |
| 24 | 新增: "github.com/sylvinus/agent-vm/internal/mobilelink" | |
| 25 | 新增: "github.com/sylvinus/agent-vm/internal/relay" | |
| 26 | 新增:) | |
| 27 | 新增: | |
| 28 | 新增:// Build ./cmd/cage and pass its absolute path in CAGE_MOBILE_E2E_BINARY. | |
| 29 | 新增:// This uses the actual desktop control gates, CLAUDE_CAGE_CONFIG isolation and | |
| 30 | 新增:// server-entry command. An isolated profile suffices; no VM or model is used. | |
| 31 | 新增:func TestIsolatedWorkbench(t *testing.T) { | |
| 32 | 新增: cage := os.Getenv("CAGE_MOBILE_E2E_BINARY") | |
| 33 | 新增: if cage == "" { | |
| 34 | 新增: t.Skip("set CAGE_MOBILE_E2E_BINARY to a newly built cage binary") | |
| 35 | 新增: } | |
| 36 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second) | |
| 37 | 新增: defer cancel() | |
| 38 | 新增: dir := t.TempDir() | |
| 39 | 新增: profile := filepath.Join(dir, "profile") | |
| 40 | 新增: if err := os.Mkdir(profile, 0700); err != nil { | |
| 41 | 新增: t.Fatal(err) | |
| 42 | 新增: } | |
| 43 | 新增: config := filepath.Join(profile, "config.json") | |
| 44 | 新增: service := exec.CommandContext(ctx, cage, "serve") | |
| 45 | 新增: service.Env = append(os.Environ(), "CLAUDE_CAGE_CONFIG="+config) | |
| 46 | 新增: if err := service.Start(); err != nil { | |
| 47 | 新增: t.Fatal(err) | |
| 48 | 新增: } | |
| 49 | 新增: defer func() { _ = service.Process.Kill(); _ = service.Wait() }() | |
| 50 | 新增: awaitFile := func(file string) []byte { | |
| 51 | 新增: t.Helper() | |
| 52 | 新增: for ctx.Err() == nil { | |
| 53 | 新增: data, err := os.ReadFile(file) | |
| 54 | 新增: if err == nil && len(data) > 0 { | |
| 55 | 新增: return data | |
| 56 | 新增: } | |
| 57 | 新增: time.Sleep(20 * time.Millisecond) | |
| 58 | 新增: } | |
| 59 | 新增: t.Fatal("timed out waiting for isolated process output") | |
| 60 | 新增: return nil | |
| 61 | 新增: } | |
| 62 | 新增: var control struct { | |
| 63 | 新增: Port json.Number | |
| 64 | 新增: Token string | |
| 65 | 新增: } | |
| 66 | 新增: if err := json.Unmarshal(awaitFile(filepath.Join(profile, "control.json")), &control); err != nil { | |
| 67 | 新增: t.Fatal("invalid isolated controller record") | |
| 68 | 新增: } | |
| 69 | 新增: desktopOrigin := "http://localhost:" + control.Port.String() | |
| 70 | 新增: jar, _ := cookiejar.New(nil) | |
| 71 | 新增: browser := &http.Client{Jar: jar, Transport: &http.Transport{Proxy: nil}, Timeout: 8 * time.Second} | |
| 72 | 新增: defer browser.CloseIdleConnections() | |
| 73 | 新增: call := func(origin, method, route string, body any, want int) []byte { | |
| 74 | 新增: t.Helper() | |
| 75 | 新增: var data []byte | |
| 76 | 新增: if body != nil { | |
| 77 | 新增: var err error | |
| 78 | 新增: data, err = json.Marshal(body) | |
| 79 | 新增: if err != nil { | |
| 80 | 新增: t.Fatal(err) | |
| 81 | 新增: } | |
| 82 | 新增: } | |
| 83 | 新增: req, err := http.NewRequestWithContext(ctx, method, origin+route, bytes.NewReader(data)) | |
| 84 | 新增: if err != nil { | |
| 85 | 新增: t.Fatal("invalid test URL") | |
| 86 | 新增: } | |
| 87 | 新增: req.Header.Set("Origin", origin) | |
| 88 | 新增: req.Header.Set("Content-Type", "application/json") | |
| 89 | 新增: res, err := browser.Do(req) | |
| 90 | 新增: if err != nil { | |
| 91 | 新增: t.Fatalf("request to %s failed", route) | |
| 92 | 新增: } | |
| 93 | 新增: defer res.Body.Close() | |
| 94 | 新增: if res.StatusCode != want { | |
| 95 | 新增: t.Fatalf("%s %s: status %d, want %d", method, route, res.StatusCode, want) | |
| 96 | 新增: } | |
| 97 | 新增: data, err = io.ReadAll(io.LimitReader(res.Body, 4<<20)) | |
| 98 | 新增: if err != nil { | |
| 99 | 新增: t.Fatal(err) | |
| 100 | 新增: } | |
| 101 | 新增: return data | |
| 102 | 新增: } | |
| 103 | 新增: var launch struct{ URL string } | |
| 104 | 新增: if json.Unmarshal(call(desktopOrigin, "POST", "/api/launch", map[string]string{"token": control.Token}, 200), &launch) != nil { | |
| 105 | 新增: t.Fatal("invalid local launch") | |
| 106 | 新增: } | |
| 107 | 新增: entry, err := url.Parse(launch.URL) | |
| 108 | 新增: if err != nil { | |
| 109 | 新增: t.Fatal("invalid local entry") | |
| 110 | 新增: } | |
| 111 | 新增: call(desktopOrigin, "POST", "/api/session", map[string]string{"token": entry.Fragment}, 200) | |
| 112 | 新增: | |
| 113 | 新增: stateHost, stateClient := filepath.Join(dir, "host"), filepath.Join(dir, "client") | |
| 114 | 新增: hostKey, err := createIdentity(stateHost) | |
| 115 | 新增: if err != nil { | |
| 116 | 新增: t.Fatal(err) | |
| 117 | 新增: } | |
| 118 | 新增: clientKey, err := createIdentity(stateClient) | |
| 119 | 新增: if err != nil { | |
| 120 | 新增: t.Fatal(err) | |
| 121 | 新增: } | |
| 122 | 新增: if err = trust(stateHost, clientKey.Pin); err != nil { | |
| 123 | 新增: t.Fatal(err) | |
| 124 | 新增: } | |
| 125 | 新增: if err = trust(stateClient, hostKey.Pin); err != nil { | |
| 126 | 新增: t.Fatal(err) | |
| 127 | 新增: } | |
| 128 | 新增: adminBytes := make([]byte, 32) | |
| 129 | 新增: _, _ = rand.Read(adminBytes) | |
| 130 | 新增: admin := hex.EncodeToString(adminBytes) | |
| 131 | 新增: r, err := relay.New(relay.Config{AdminToken: admin}) | |
| 132 | 新增: if err != nil { | |
| 133 | 新增: t.Fatal(err) | |
| 134 | 新增: } | |
| 135 | 新增: var current atomic.Pointer[relay.Server] | |
| 136 | 新增: current.Store(r) | |
| 137 | 新增: rs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { current.Load().ServeHTTP(w, req) })) | |
| 138 | 新增: defer rs.Close() | |
| 139 | 新增: defer r.Close() | |
| 140 | 新增: tokenFile, inviteFile := filepath.Join(dir, "admin"), filepath.Join(dir, "invitation") | |
| 141 | 新增: if err := writeNewPrivate(tokenFile, []byte(admin)); err != nil { | |
| 142 | 新增: t.Fatal(err) | |
| 143 | 新增: } | |
| 144 | 新增: start := func(args ...string) func() { | |
| 145 | 新增: t.Helper() | |
| 146 | 新增: child, stop := context.WithCancel(ctx) | |
| 147 | 新增: done := make(chan error, 1) | |
| 148 | 新增: go func() { done <- run(child, args, io.Discard, io.Discard) }() | |
| 149 | 新增: var once sync.Once | |
| 150 | 新增: closeService := func() { | |
| 151 | 新增: once.Do(func() { | |
| 152 | 新增: stop() | |
| 153 | 新增: select { | |
| 154 | 新增: case <-done: | |
| 155 | 新增: case <-time.After(3 * time.Second): | |
| 156 | 新增: t.Error("link command did not exit") | |
| 157 | 新增: } | |
| 158 | 新增: }) | |
| 159 | 新增: } | |
| 160 | 新增: t.Cleanup(closeService) | |
| 161 | 新增: return closeService | |
| 162 | 新增: } | |
| 163 | 新增: start("host", "--state", stateHost, "--relay", rs.URL, "--admin-token-file", tokenFile, "--invitation-out", inviteFile, "--cage-bin", cage, "--config", config) | |
| 164 | 新增: awaitFile(inviteFile) | |
| 165 | 新增: if os.Getenv("CAGE_MOBILE_E2E_DELAY_JOIN") == "1" { | |
| 166 | 新增: // A user may take longer than the 15-second TLS handshake deadline to | |
| 167 | 新增: // transport a private invitation. This wait belongs to relay admission. | |
| 168 | 新增: time.Sleep(16 * time.Second) | |
| 169 | 新增: } | |
| 170 | 新增: webDir := filepath.Join(dir, "web") | |
| 171 | 新增: if err := os.Mkdir(webDir, 0700); err != nil { | |
| 172 | 新增: t.Fatal(err) | |
| 173 | 新增: } | |
| 174 | 新增: if err := os.WriteFile(filepath.Join(webDir, "mobile.html"), []byte("isolated mobile page"), 0600); err != nil { | |
| 175 | 新增: t.Fatal(err) | |
| 176 | 新增: } | |
| 177 | 新增: launchFile := filepath.Join(dir, "launch.html") | |
| 178 | 新增: start("client", "--state", stateClient, "--relay", rs.URL, "--invitation-file", inviteFile, "--web-dir", webDir, "--launch-file", launchFile) | |
| 179 | 新增: match := regexp.MustCompile(`url=(http://[^"]+)`).FindSubmatch(awaitFile(launchFile)) | |
| 180 | 新增: if len(match) != 2 { | |
| 181 | 新增: t.Fatal("invalid private launch page") | |
| 182 | 新增: } | |
| 183 | 新增: mobileEntry, err := url.Parse(string(match[1])) | |
| 184 | 新增: if err != nil { | |
| 185 | 新增: t.Fatal("invalid local mobile origin") | |
| 186 | 新增: } | |
| 187 | 新增: mobileOrigin := mobileEntry.Scheme + "://" + mobileEntry.Host | |
| 188 | 新增: call(mobileOrigin, "POST", "/link-session", map[string]string{"token": mobileEntry.Fragment}, 204) | |
| 189 | 新增: call(mobileOrigin, "GET", "/api/mobile/cli/projects", nil, 423) | |
| 190 | 新增: pass := hex.EncodeToString(adminBytes[:16]) | |
| 191 | 新增: call(desktopOrigin, "POST", "/api/account/create", map[string]string{"username": "isolated-mobile", "password": pass, "confirm_password": pass}, 200) | |
| 192 | 新增: var projects struct{ Projects []struct{ Path string } } | |
| 193 | 新增: if json.Unmarshal(call(mobileOrigin, "GET", "/api/mobile/cli/projects", nil, 200), &projects) != nil || len(projects.Projects) == 0 { | |
| 194 | 新增: t.Fatal("no projects from isolated workbench") | |
| 195 | 新增: } | |
| 196 | 新增: before := awaitFile(filepath.Join(profile, "workbench.json")) | |
| 197 | 新增: const id = "b4fc408f-a017-4b2e-b95c-744e01af058e" | |
| 198 | 新增: input := map[string]string{"id": id, "workspace": projects.Projects[0].Path} | |
| 199 | 新增: call(mobileOrigin, "POST", "/api/mobile/cli/sessions", input, 200) | |
| 200 | 新增: if !strings.Contains(string(call(mobileOrigin, "GET", "/api/mobile/cli/sessions", nil, 200)), id) { | |
| 201 | 新增: t.Fatal("created session missing") | |
| 202 | 新增: } | |
| 203 | 新增: var snapshot struct{ Revision json.Number } | |
| 204 | 新增: if json.Unmarshal(call(mobileOrigin, "GET", "/api/mobile/cli/sessions/"+id, nil, 200), &snapshot) != nil || snapshot.Revision == "" { | |
| 205 | 新增: t.Fatal("invalid real session revision") | |
| 206 | 新增: } | |
| 207 | 新增: call(mobileOrigin, "GET", "/api/mobile/cli/sessions/"+id+"?after="+snapshot.Revision.String(), nil, 204) | |
| 208 | 新增: if after := awaitFile(filepath.Join(profile, "workbench.json")); !bytes.Equal(before, after) { | |
| 209 | 新增: t.Fatal("mobile session changed desktop preferences") | |
| 210 | 新增: } | |
| 211 | 新增: call(mobileOrigin, "POST", "/api/account/lock", map[string]string{}, 404) | |
| 212 | 新增: call(desktopOrigin, "POST", "/api/account/lock", map[string]string{}, 200) | |
| 213 | 新增: call(mobileOrigin, "GET", "/api/mobile/cli/sessions/"+id, nil, 423) | |
| 214 | 新增: call(desktopOrigin, "POST", "/api/account/unlock", map[string]string{"password": pass}, 200) | |
| 215 | 新增: savedFile := filepath.Join(dir, "saved-connection.json") | |
| 216 | 新增: stopHost := start("host", "--state", stateHost, "--relay", rs.URL, "--admin-token-file", tokenFile, "--connection-out", savedFile, "--cage-bin", cage, "--config", config) | |
| 217 | 新增: awaitFile(savedFile) | |
| 218 | 新增: var saved connectionFile | |
| 219 | 新增: if decodePrivateJSON(savedFile, &saved) != nil || !saved.valid() { | |
| 220 | 新增: t.Fatal("invalid exported saved connection") | |
| 221 | 新增: } | |
| 222 | 新增: previous := "" | |
| 223 | 新增: connectSaved := func() *mobilelink.Client { | |
| 224 | 新增: t.Helper() | |
| 225 | 新增: wait, cancel := context.WithTimeout(ctx, 6*time.Second) | |
| 226 | 新增: defer cancel() | |
| 227 | 新增: for wait.Err() == nil { | |
| 228 | 新增: room, err := resolveSaved(wait, savedFile, rs.URL, hostKey.Pin) | |
| 229 | 新增: if err == nil && room.ID != previous { | |
| 230 | 新增: c, err := mobilelink.ConnectClient(wait, rs.URL, room.ID, room.Token, clientKey, hostKey.Pin) | |
| 231 | 新增: if err != nil { | |
| 232 | 新增: t.Fatal(err) | |
| 233 | 新增: } | |
| 234 | 新增: v, err := c.Do(ctx, "GET", "/api/mobile/cli/sessions/"+id, nil) | |
| 235 | 新增: if err != nil || v.Status != 200 || !strings.Contains(string(v.Body), id) { | |
| 236 | 新增: c.Close() | |
| 237 | 新增: t.Fatal("saved connection lost original host session") | |
| 238 | 新增: } | |
| 239 | 新增: previous = room.ID | |
| 240 | 新增: return c | |
| 241 | 新增: } | |
| 242 | 新增: time.Sleep(30 * time.Millisecond) | |
| 243 | 新增: } | |
| 244 | 新增: t.Fatal("no new room from saved host") | |
| 245 | 新增: return nil | |
| 246 | 新增: } | |
| 247 | 新增: first := connectSaved() | |
| 248 | 新增: first.Close() | |
| 249 | 新增: second := connectSaved() | |
| 250 | 新增: newRelay, err := relay.New(relay.Config{AdminToken: admin}) | |
| 251 | 新增: if err != nil { | |
| 252 | 新增: t.Fatal(err) | |
| 253 | 新增: } | |
| 254 | 新增: defer newRelay.Close() | |
| 255 | 新增: current.Store(newRelay) | |
| 256 | 新增: r.Close() | |
| 257 | 新增: second.Close() | |
| 258 | 新增: afterRelayRestart := connectSaved() | |
| 259 | 新增: stopHost() | |
| 260 | 新增: afterRelayRestart.Close() | |
| 261 | 新增: start("host", "--state", stateHost, "--serve-saved") | |
| 262 | 新增: afterHostRestart := connectSaved() | |
| 263 | 新增: if err := run(ctx, []string{"revoke", "--state", stateHost}, io.Discard, io.Discard); err != nil { | |
| 264 | 新增: t.Fatal(err) | |
| 265 | 新增: } | |
| 266 | 新增: cutoff := time.Now().Add(3 * time.Second) | |
| 267 | 新增: for { | |
| 268 | 新增: _, err := afterHostRestart.Do(ctx, "GET", "/api/mobile/cli/sessions/"+id, nil) | |
| 269 | 新增: if err != nil { | |
| 270 | 新增: break | |
| 271 | 新增: } | |
| 272 | 新增: if time.Now().After(cutoff) { | |
| 273 | 新增: t.Fatal("revoked connection stayed usable") | |
| 274 | 新增: } | |
| 275 | 新增: time.Sleep(50 * time.Millisecond) | |
| 276 | 新增: } | |
| 277 | 新增: afterHostRestart.Close() | |
| 278 | 新增: if _, err := mobilelink.LookupRoom(ctx, rs.URL, saved.LookupToken); err == nil { | |
| 279 | 新增: t.Fatal("revoked token still resolved") | |
| 280 | 新增: } | |
| 281 | 新增: if err := trust(stateHost, clientKey.Pin); err != nil { | |
| 282 | 新增: t.Fatal(err) | |
| 283 | 新增: } | |
| 284 | 新增: newSaved, err := configureSavedHost(stateHost, filepath.Join(dir, "renewed.json"), hostKey.Pin, clientKey.Pin, hostSettings{Relay: rs.URL, AdminFile: tokenFile, CageBinary: cage, Config: config}) | |
| 285 | 新增: if err != nil || newSaved.Connection.LookupToken == saved.LookupToken { | |
| 286 | 新增: t.Fatal("new authorization must rotate the lookup token") | |
| 287 | 新增: } | |
| 288 | 新增:} | |
| @@ -0,0 +1,149 @@ | ||
| 1 | 新增:// cage-relay forwards an opaque stream between two outbound connections. | |
| 2 | 新增:// Device authentication and application authorization belong to the peers. | |
| 3 | 新增:package main | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bytes" | |
| 7 | 新增: "context" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "flag" | |
| 10 | 新增: "fmt" | |
| 11 | 新增: "io" | |
| 12 | 新增: "log" | |
| 13 | 新增: "net" | |
| 14 | 新增: "net/http" | |
| 15 | 新增: "os" | |
| 16 | 新增: "os/signal" | |
| 17 | 新增: "runtime" | |
| 18 | 新增: "syscall" | |
| 19 | 新增: "time" | |
| 20 | 新增: | |
| 21 | 新增: "github.com/sylvinus/agent-vm/internal/relay" | |
| 22 | 新增:) | |
| 23 | 新增: | |
| 24 | 新增:const maxTokenBytes = 4096 | |
| 25 | 新增: | |
| 26 | 新增:func main() { | |
| 27 | 新增: ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) | |
| 28 | 新增: defer stop() | |
| 29 | 新增: if err := run(ctx, os.Args[1:], os.Stderr); err != nil { | |
| 30 | 新增: fmt.Fprintln(os.Stderr, "cage-relay:", err) | |
| 31 | 新增: os.Exit(1) | |
| 32 | 新增: } | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:func run(ctx context.Context, args []string, output io.Writer) error { | |
| 36 | 新增: flags := flag.NewFlagSet("cage-relay", flag.ContinueOnError) | |
| 37 | 新增: flags.SetOutput(output) | |
| 38 | 新增: listen := flags.String("listen", "127.0.0.1:8787", "HTTP listen address; place public deployments behind TLS") | |
| 39 | 新增: tokenFile := flags.String("token-file", "", "required file containing the relay administration token") | |
| 40 | 新增: publicRooms := flags.Bool("public-rooms", false, "allow room creation without a token; enforce quotas at the public ingress") | |
| 41 | 新增: maxRooms := flags.Int("max-rooms", 128, "maximum pending and connected rooms") | |
| 42 | 新增: pairTimeout := flags.Duration("pair-timeout", 2*time.Minute, "time allowed for both peers to connect") | |
| 43 | 新增: idleTimeout := flags.Duration("idle-timeout", 5*time.Minute, "maximum connection idle time") | |
| 44 | 新增: if err := flags.Parse(args); err != nil { | |
| 45 | 新增: if errors.Is(err, flag.ErrHelp) { | |
| 46 | 新增: return nil | |
| 47 | 新增: } | |
| 48 | 新增: return err | |
| 49 | 新增: } | |
| 50 | 新增: if flags.NArg() != 0 { | |
| 51 | 新增: return errors.New("positional arguments are not supported") | |
| 52 | 新增: } | |
| 53 | 新增: if *maxRooms < 1 || *pairTimeout <= 0 || *idleTimeout <= 0 { | |
| 54 | 新增: return errors.New("max-rooms, pair-timeout and idle-timeout must be positive") | |
| 55 | 新增: } | |
| 56 | 新增: token, err := readTokenFile(*tokenFile) | |
| 57 | 新增: if err != nil { | |
| 58 | 新增: return err | |
| 59 | 新增: } | |
| 60 | 新增: server, err := relay.New(relay.Config{ | |
| 61 | 新增: AdminToken: token, PublicRooms: *publicRooms, MaxRooms: *maxRooms, | |
| 62 | 新增: PairTimeout: *pairTimeout, IdleTimeout: *idleTimeout, | |
| 63 | 新增: }) | |
| 64 | 新增: if err != nil { | |
| 65 | 新增: return err | |
| 66 | 新增: } | |
| 67 | 新增: listener, err := net.Listen("tcp", *listen) | |
| 68 | 新增: if err != nil { | |
| 69 | 新增: _ = server.Close() | |
| 70 | 新增: return fmt.Errorf("listen: %w", err) | |
| 71 | 新增: } | |
| 72 | 新增: logger := log.New(output, "cage-relay: ", log.LstdFlags) | |
| 73 | 新增: logger.Printf("listening on %s", listener.Addr()) | |
| 74 | 新增: return serve(ctx, listener, server, logger) | |
| 75 | 新增:} | |
| 76 | 新增: | |
| 77 | 新增:func readTokenFile(name string) (string, error) { | |
| 78 | 新增: if name == "" { | |
| 79 | 新增: return "", errors.New("--token-file is required") | |
| 80 | 新增: } | |
| 81 | 新增: file, err := os.Open(name) | |
| 82 | 新增: if err != nil { | |
| 83 | 新增: return "", fmt.Errorf("open token file: %w", err) | |
| 84 | 新增: } | |
| 85 | 新增: defer file.Close() | |
| 86 | 新增: info, err := file.Stat() | |
| 87 | 新增: if err != nil { | |
| 88 | 新增: return "", fmt.Errorf("inspect token file: %w", err) | |
| 89 | 新增: } | |
| 90 | 新增: if !info.Mode().IsRegular() { | |
| 91 | 新增: return "", errors.New("token file must be a regular file") | |
| 92 | 新增: } | |
| 93 | 新增: // Windows permissions are ACL based and cannot be checked with Unix mode | |
| 94 | 新增: // bits. Deployment instructions require an owner-restricted ACL there. | |
| 95 | 新增: if runtime.GOOS != "windows" && info.Mode().Perm()&0077 != 0 { | |
| 96 | 新增: return "", errors.New("token file must not grant permissions to group or other users; use mode 0600") | |
| 97 | 新增: } | |
| 98 | 新增: // One trailing LF or CRLF is accepted, as produced by command-line secret | |
| 99 | 新增: // generators. Other whitespace is rejected instead of silently changing it. | |
| 100 | 新增: raw, err := io.ReadAll(io.LimitReader(file, maxTokenBytes+3)) | |
| 101 | 新增: if err != nil { | |
| 102 | 新增: return "", fmt.Errorf("read token file: %w", err) | |
| 103 | 新增: } | |
| 104 | 新增: defer clear(raw) | |
| 105 | 新增: value := raw | |
| 106 | 新增: if bytes.HasSuffix(value, []byte("\n")) { | |
| 107 | 新增: value = bytes.TrimSuffix(value[:len(value)-1], []byte("\r")) | |
| 108 | 新增: } | |
| 109 | 新增: if len(value) < 32 || len(value) > maxTokenBytes { | |
| 110 | 新增: return "", errors.New("token file must contain 32 to 4096 bytes, excluding its trailing newline") | |
| 111 | 新增: } | |
| 112 | 新增: for _, ch := range value { | |
| 113 | 新增: if ch < 0x21 || ch > 0x7e { | |
| 114 | 新增: return "", errors.New("token must contain visible ASCII characters without whitespace") | |
| 115 | 新增: } | |
| 116 | 新增: } | |
| 117 | 新增: return string(value), nil | |
| 118 | 新增:} | |
| 119 | 新增: | |
| 120 | 新增:func serve(ctx context.Context, listener net.Listener, relayServer *relay.Server, logger *log.Logger) error { | |
| 121 | 新增: httpServer := &http.Server{ | |
| 122 | 新增: Handler: relayServer, ErrorLog: logger, | |
| 123 | 新增: ReadHeaderTimeout: 5 * time.Second, | |
| 124 | 新增: IdleTimeout: 60 * time.Second, | |
| 125 | 新增: MaxHeaderBytes: 16 << 10, | |
| 126 | 新增: } | |
| 127 | 新增: serveErr := make(chan error, 1) | |
| 128 | 新增: go func() { serveErr <- httpServer.Serve(listener) }() | |
| 129 | 新增: select { | |
| 130 | 新增: case err := <-serveErr: | |
| 131 | 新增: closeErr := relayServer.Close() | |
| 132 | 新增: if errors.Is(err, http.ErrServerClosed) { | |
| 133 | 新增: err = nil | |
| 134 | 新增: } | |
| 135 | 新增: return errors.Join(err, closeErr) | |
| 136 | 新增: case <-ctx.Done(): | |
| 137 | 新增: // http.Server.Shutdown does not close upgraded WebSocket connections. | |
| 138 | 新增: // Stop relay rooms first so peers and pending joins are released too. | |
| 139 | 新增: closeErr := relayServer.Close() | |
| 140 | 新增: shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | |
| 141 | 新增: defer cancel() | |
| 142 | 新增: shutdownErr := httpServer.Shutdown(shutdownCtx) | |
| 143 | 新增: if shutdownErr != nil { | |
| 144 | 新增: _ = httpServer.Close() | |
| 145 | 新增: } | |
| 146 | 新增: <-serveErr | |
| 147 | 新增: return errors.Join(closeErr, shutdownErr) | |
| 148 | 新增: } | |
| 149 | 新增:} | |
| @@ -0,0 +1,158 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "io" | |
| 7 | 新增: "log" | |
| 8 | 新增: "net" | |
| 9 | 新增: "net/http" | |
| 10 | 新增: "os" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "runtime" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "testing" | |
| 15 | 新增: "time" | |
| 16 | 新增: | |
| 17 | 新增: "github.com/gorilla/websocket" | |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/relay" | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 21 | 新增:func TestTokenFileValidation(t *testing.T) { | |
| 22 | 新增: secret := strings.Repeat("a", 64) | |
| 23 | 新增: for _, tc := range []struct { | |
| 24 | 新增: name string | |
| 25 | 新增: content string | |
| 26 | 新增: valid bool | |
| 27 | 新增: }{ | |
| 28 | 新增: {"generated", secret + "\n", true}, | |
| 29 | 新增: {"windows-newline", secret + "\r\n", true}, | |
| 30 | 新增: {"bare-carriage-return", secret + "\r", false}, | |
| 31 | 新增: {"no-newline", secret, true}, | |
| 32 | 新增: {"too-short", strings.Repeat("a", 31), false}, | |
| 33 | 新增: {"too-large", strings.Repeat("a", maxTokenBytes+1), false}, | |
| 34 | 新增: {"embedded-newline", secret + "\nignored", false}, | |
| 35 | 新增: {"space", " " + secret, false}, | |
| 36 | 新增: {"control", secret + "\x00", false}, | |
| 37 | 新增: {"non-ascii", secret + "密钥", false}, | |
| 38 | 新增: } { | |
| 39 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 40 | 新增: name := filepath.Join(t.TempDir(), "token") | |
| 41 | 新增: if err := os.WriteFile(name, []byte(tc.content), 0600); err != nil { | |
| 42 | 新增: t.Fatal(err) | |
| 43 | 新增: } | |
| 44 | 新增: got, err := readTokenFile(name) | |
| 45 | 新增: if (err == nil) != tc.valid { | |
| 46 | 新增: t.Fatalf("valid=%v, error=%v", tc.valid, err) | |
| 47 | 新增: } | |
| 48 | 新增: if tc.valid && got != secret { | |
| 49 | 新增: t.Fatal("token changed during parsing") | |
| 50 | 新增: } | |
| 51 | 新增: if err != nil && strings.Contains(err.Error(), secret) { | |
| 52 | 新增: t.Fatal("validation error disclosed the token") | |
| 53 | 新增: } | |
| 54 | 新增: }) | |
| 55 | 新增: } | |
| 56 | 新增: if _, err := readTokenFile(""); err == nil { | |
| 57 | 新增: t.Fatal("missing token file accepted") | |
| 58 | 新增: } | |
| 59 | 新增: if _, err := readTokenFile(t.TempDir()); err == nil { | |
| 60 | 新增: t.Fatal("directory accepted as token file") | |
| 61 | 新增: } | |
| 62 | 新增:} | |
| 63 | 新增: | |
| 64 | 新增:func TestTokenFileRejectsSharedUnixPermissions(t *testing.T) { | |
| 65 | 新增: if runtime.GOOS == "windows" { | |
| 66 | 新增: t.Skip("Windows uses ACLs") | |
| 67 | 新增: } | |
| 68 | 新增: name := filepath.Join(t.TempDir(), "token") | |
| 69 | 新增: if err := os.WriteFile(name, []byte(strings.Repeat("a", 64)), 0600); err != nil { | |
| 70 | 新增: t.Fatal(err) | |
| 71 | 新增: } | |
| 72 | 新增: for _, mode := range []os.FileMode{0640, 0604, 0620, 0601} { | |
| 73 | 新增: if err := os.Chmod(name, mode); err != nil { | |
| 74 | 新增: t.Fatal(err) | |
| 75 | 新增: } | |
| 76 | 新增: if _, err := readTokenFile(name); err == nil { | |
| 77 | 新增: t.Fatalf("token with mode %04o accepted", mode) | |
| 78 | 新增: } | |
| 79 | 新增: } | |
| 80 | 新增:} | |
| 81 | 新增: | |
| 82 | 新增:func TestRunRejectsMissingTokenAndInvalidLimits(t *testing.T) { | |
| 83 | 新增: for _, args := range [][]string{nil, {"--max-rooms=0"}, {"--pair-timeout=0s"}, {"--idle-timeout=-1s"}, {"unexpected"}} { | |
| 84 | 新增: if err := run(context.Background(), args, io.Discard); err == nil { | |
| 85 | 新增: t.Fatalf("invalid arguments accepted: %v", args) | |
| 86 | 新增: } | |
| 87 | 新增: } | |
| 88 | 新增:} | |
| 89 | 新增: | |
| 90 | 新增:func TestShutdownClosesPairedWebSockets(t *testing.T) { | |
| 91 | 新增: secret := strings.Repeat("x", 64) | |
| 92 | 新增: server, err := relay.New(relay.Config{AdminToken: secret}) | |
| 93 | 新增: if err != nil { | |
| 94 | 新增: t.Fatal(err) | |
| 95 | 新增: } | |
| 96 | 新增: listener, err := net.Listen("tcp", "127.0.0.1:0") | |
| 97 | 新增: if err != nil { | |
| 98 | 新增: t.Fatal(err) | |
| 99 | 新增: } | |
| 100 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 101 | 新增: defer cancel() | |
| 102 | 新增: defer server.Close() | |
| 103 | 新增: defer listener.Close() | |
| 104 | 新增: done := make(chan error, 1) | |
| 105 | 新增: go func() { done <- serve(ctx, listener, server, log.New(io.Discard, "", 0)) }() | |
| 106 | 新增: base := listener.Addr().String() | |
| 107 | 新增: request, err := http.NewRequest(http.MethodPost, "http://"+base+"/v1/rooms", nil) | |
| 108 | 新增: if err != nil { | |
| 109 | 新增: t.Fatal(err) | |
| 110 | 新增: } | |
| 111 | 新增: request.Header.Set("Authorization", "Bearer "+secret) | |
| 112 | 新增: client := &http.Client{Timeout: 3 * time.Second} | |
| 113 | 新增: response, err := client.Do(request) | |
| 114 | 新增: if err != nil { | |
| 115 | 新增: t.Fatal(err) | |
| 116 | 新增: } | |
| 117 | 新增: var invitation relay.Invitation | |
| 118 | 新增: err = json.NewDecoder(response.Body).Decode(&invitation) | |
| 119 | 新增: response.Body.Close() | |
| 120 | 新增: if err != nil { | |
| 121 | 新增: t.Fatal(err) | |
| 122 | 新增: } | |
| 123 | 新增: if response.StatusCode != http.StatusCreated { | |
| 124 | 新增: t.Fatalf("create room status=%d", response.StatusCode) | |
| 125 | 新增: } | |
| 126 | 新增: dialer := websocket.Dialer{HandshakeTimeout: 3 * time.Second} | |
| 127 | 新增: connect := func(role, token string) *websocket.Conn { | |
| 128 | 新增: t.Helper() | |
| 129 | 新增: header := http.Header{"Authorization": []string{"Bearer " + token}} | |
| 130 | 新增: connection, _, err := dialer.Dial("ws://"+base+"/v1/rooms/"+invitation.ID+"/"+role, header) | |
| 131 | 新增: if err != nil { | |
| 132 | 新增: t.Fatal(err) | |
| 133 | 新增: } | |
| 134 | 新增: t.Cleanup(func() { connection.Close() }) | |
| 135 | 新增: return connection | |
| 136 | 新增: } | |
| 137 | 新增: host := connect("host", invitation.HostToken) | |
| 138 | 新增: peer := connect("client", invitation.ClientToken) | |
| 139 | 新增: cancel() | |
| 140 | 新增: select { | |
| 141 | 新增: case err := <-done: | |
| 142 | 新增: if err != nil { | |
| 143 | 新增: t.Fatal(err) | |
| 144 | 新增: } | |
| 145 | 新增: case <-time.After(3 * time.Second): | |
| 146 | 新增: t.Fatal("shutdown did not complete") | |
| 147 | 新增: } | |
| 148 | 新增: for _, connection := range []*websocket.Conn{host, peer} { | |
| 149 | 新增: _ = connection.SetReadDeadline(time.Now().Add(time.Second)) | |
| 150 | 新增: _, _, err := connection.ReadMessage() | |
| 151 | 新增: if err == nil { | |
| 152 | 新增: t.Fatal("WebSocket stayed usable after shutdown") | |
| 153 | 新增: } | |
| 154 | 新增: if timeout, ok := err.(net.Error); ok && timeout.Timeout() { | |
| 155 | 新增: t.Fatal("WebSocket was not closed by shutdown") | |
| 156 | 新增: } | |
| 157 | 新增: } | |
| 158 | 新增:} | |
| @@ -0,0 +1,22 @@ | ||
| 1 | 新增:{ | |
| 2 | 新增: admin off | |
| 3 | 新增: log default { | |
| 4 | 新增: format filter { | |
| 5 | 新增: wrap json | |
| 6 | 新增: fields { | |
| 7 | 新增: request>uri delete | |
| 8 | 新增: request>headers delete | |
| 9 | 新增: } | |
| 10 | 新增: } | |
| 11 | 新增: } | |
| 12 | 新增:} | |
| 13 | 新增: | |
| 14 | 新增:{$RELAY_DOMAIN} { | |
| 15 | 新增: @relay path /healthz /v1/rooms /v1/rooms/* /v1/invitation | |
| 16 | 新增: handle @relay { | |
| 17 | 新增: reverse_proxy relay:8787 | |
| 18 | 新增: } | |
| 19 | 新增: handle { | |
| 20 | 新增: respond 404 | |
| 21 | 新增: } | |
| 22 | 新增:} | |
| @@ -0,0 +1,15 @@ | ||
| 1 | 新增:# Build only the relay. The fixed vendored modules preserve go.mod replacements; | |
| 2 | 新增:# this target does not embed or download Cage virtual-machine images. | |
| 3 | 新增:FROM golang:1.26.10-bookworm AS build | |
| 4 | 新增:WORKDIR /src | |
| 5 | 新增:COPY go.mod go.sum ./ | |
| 6 | 新增:COPY third_party ./third_party | |
| 7 | 新增:COPY internal/relay ./internal/relay | |
| 8 | 新增:COPY cmd/cage-relay ./cmd/cage-relay | |
| 9 | 新增:RUN CGO_ENABLED=0 go build -mod=readonly -trimpath -ldflags="-s -w" -o /out/cage-relay ./cmd/cage-relay | |
| 10 | 新增: | |
| 11 | 新增:FROM scratch | |
| 12 | 新增:COPY --from=build /out/cage-relay /cage-relay | |
| 13 | 新增:USER 65532:65532 | |
| 14 | 新增:EXPOSE 8787 | |
| 15 | 新增:ENTRYPOINT ["/cage-relay"] | |
| @@ -0,0 +1,96 @@ | ||
| 1 | 新增:# 自建 Cage 中继 | |
| 2 | 新增: | |
| 3 | 新增:此目录面向维护自有服务器的开发者,用于部署两个已授权设备之间的连接转发服务。电脑和客户端分别主动连接服务器,服务器将同一房间内的两条 WebSocket 连接互相转发。 | |
| 4 | 新增: | |
| 5 | 新增:部署中继后,使用主机连接助手登记手机的公钥指纹。Android/iOS 客户端通过设备通道操作 Claude Code CLI 会话。设备信任、保存连接与撤销由端点负责。[移动客户端](../../mobile/README.md) · [主机连接助手](../../cmd/cage-mobile-link/README.md) | |
| 6 | 新增: | |
| 7 | 新增:普通用户可直接使用[官方中继](../../mobile/README.md)。本文的自建部署默认要求管理令牌。如果运营者需要允许任何电脑创建房间,可显式启用 `--public-rooms`。应在公网入口按源 IP 限制创建频率和并发连接数,同时保留中继的全局房间上限。公开创建房间时仍需在手机和电脑上互信指纹才能操作工作台。 | |
| 8 | 新增: | |
| 9 | 新增:## 连接与密钥的归属 | |
| 10 | 新增: | |
| 11 | 新增:中继管理令牌仅用于创建短期连接房间。每个房间返回独立的主机令牌、客户端令牌和过期时间;两端各使用自己的令牌连接一次。两端之间的业务数据须由 `internal/remotelink` 的 TLS 1.3 双向证书验证通道保护,端点校验预先信任的对端身份后才能发送业务数据。中继房间令牌只代表一次连接资格,不能替代设备身份或 Cage 的账户授权。 | |
| 12 | 新增: | |
| 13 | 新增:HTTPS/WSS 保护设备到中继的外层连接,端到端 TLS 保护中继内转发的业务内容。中继实现本身只转发不透明二进制帧,无法强迫任意自编客户端加密;客户端必须使用端到端通道。部署者仍能观察连接地址、时间与流量规模。 | |
| 14 | 新增: | |
| 15 | 新增:房间只存在于内存中。未在配对期限内到齐的连接会被关闭;一端断开后需要创建新房间。服务重启也会中断所有房间,恢复业务状态由设备侧负责。默认最多 128 个房间,配对期限 2 分钟,空闲期限 5 分钟;单个 WebSocket 消息不得超过 64 KiB。 | |
| 16 | 新增: | |
| 17 | 新增:本服务不接收 SSH 客户端、普通 HTTP 代理、任意浏览器 WebSocket 或 VNC 客户端。浏览器发起的带 `Origin` 请求会被拒绝,原生客户端负责建立设备通道。现有 Cage 的 SSH 远程主机连接使用另一套启动与认证流程,不能把 SSH 主机地址直接替换成此中继地址。 | |
| 18 | 新增: | |
| 19 | 新增:## 在 Linux 服务器部署 | |
| 20 | 新增: | |
| 21 | 新增:准备一台安装 Docker Engine 和 Compose 的 Linux 服务器,以及指向该服务器的域名。仅开放 TCP 80、443;Caddy 使用域名取得可信证书,转发到容器内部的中继服务。部署配置不会将中继的 8787 端口映射到主机。 | |
| 22 | 新增: | |
| 23 | 新增:在仓库根目录执行以下命令。密钥保存在仓库外,`openssl` 不会将内容输出到终端;使用当前部署用户运行后续 Compose 命令。 | |
| 24 | 新增: | |
| 25 | 新增:```sh | |
| 26 | 新增:install -d -m 700 "$HOME/.config/cage-relay" | |
| 27 | 新增:( | |
| 28 | 新增: umask 077 | |
| 29 | 新增: set -C | |
| 30 | 新增: openssl rand -hex 32 > "$HOME/.config/cage-relay/admin-token" | |
| 31 | 新增:) | |
| 32 | 新增:chmod 600 "$HOME/.config/cage-relay/admin-token" | |
| 33 | 新增:export RELAY_TOKEN_FILE="$HOME/.config/cage-relay/admin-token" | |
| 34 | 新增:export RELAY_UID="$(id -u)" | |
| 35 | 新增:export RELAY_GID="$(id -g)" | |
| 36 | 新增:export RELAY_DOMAIN="relay.example.com" | |
| 37 | 新增:docker compose -f deploy/relay/compose.yaml config --quiet | |
| 38 | 新增:docker compose -f deploy/relay/compose.yaml up -d --build | |
| 39 | 新增:``` | |
| 40 | 新增: | |
| 41 | 新增:将示例域名改为自己的域名。密钥生成命令拒绝覆盖已有文件;已有部署直接复用原文件。Compose 缺少域名、密钥路径或文件所有者标识时会直接报错。Go 构建镜像固定为与项目声明一致的 `1.26.10`,Caddy 固定为 `2.11.8-alpine`;镜像升级需修改并验证配置,不使用 `latest`。 | |
| 42 | 新增: | |
| 43 | 新增:密钥作为只读 Compose secret 挂载,中继容器以密钥文件所有者的 UID/GID 运行。Docker Compose 对文件来源 secret 使用绑定挂载,不能依赖 secret 的 `uid`、`gid` 或 `mode` 设置替代主机文件权限。[Docker secrets 文档](https://docs.docker.com/compose/how-tos/use-secrets/) | |
| 44 | 新增: | |
| 45 | 新增:中继容器使用只读文件系统、移除所有 Linux capabilities,并且只接入内部网络。Caddy 同时连接外网与内部网络,证书保存在 `caddy_data` 卷中。配置没有启用访问日志,默认结构化日志会移除请求路径和请求头,避免记录房间地址及认证信息。[Caddy 反向代理文档](https://caddyserver.com/docs/caddyfile/directives/reverse_proxy) | |
| 46 | 新增: | |
| 47 | 新增:使用不含密钥的健康检查确认 HTTPS 和服务监听正常: | |
| 48 | 新增: | |
| 49 | 新增:```sh | |
| 50 | 新增:curl --fail --silent --show-error "https://${RELAY_DOMAIN}/healthz" | |
| 51 | 新增:docker compose -f deploy/relay/compose.yaml ps | |
| 52 | 新增:``` | |
| 53 | 新增: | |
| 54 | 新增:健康检查返回 `ok` 仅表示中继可响应;还需要使用两个持有对端信任信息的测试端点验证加密握手、转发、断线和身份拒绝。它不能证明移动工作台已经可用。 | |
| 55 | 新增: | |
| 56 | 新增:## 本机开发与直接运行 | |
| 57 | 新增: | |
| 58 | 新增:在仓库根目录构建并启动: | |
| 59 | 新增: | |
| 60 | 新增:```sh | |
| 61 | 新增:go build -o /tmp/cage-relay ./cmd/cage-relay | |
| 62 | 新增:/tmp/cage-relay --token-file "$HOME/.config/cage-relay/admin-token" | |
| 63 | 新增:``` | |
| 64 | 新增: | |
| 65 | 新增:程序默认监听 `127.0.0.1:8787`,不主动开放公网。修改监听地址必须显式传入 `--listen`;公网部署应通过可信 TLS 入口,不能直接暴露明文 HTTP。启动日志只记录监听地址,不输出令牌、邀请内容或房间 URL。 | |
| 66 | 新增: | |
| 67 | 新增:| 参数 | 默认值 | 含义 | | |
| 68 | 新增:| --- | --- | --- | | |
| 69 | 新增:| `--listen` | `127.0.0.1:8787` | HTTP 监听地址 | | |
| 70 | 新增:| `--token-file` | 必填 | 中继管理令牌文件 | | |
| 71 | 新增:| `--max-rooms` | `128` | 等待连接和已连接房间的总上限 | | |
| 72 | 新增:| `--pair-timeout` | `2m` | 等待两端到齐的期限 | | |
| 73 | 新增:| `--idle-timeout` | `5m` | 连接空闲期限 | | |
| 74 | 新增: | |
| 75 | 新增:令牌需包含 32–4096 字节的无空白可见 ASCII 字符,允许末尾一个 LF 或 CRLF。macOS/Linux 拒绝组或其他用户具有权限的文件,建议使用 `0600`。Windows 文件权限采用 ACL,程序不通过 Unix 权限位推断访问范围;运行前应关闭继承,并仅允许服务账户及必要的系统管理员访问。Windows 和 macOS 可运行同一 Go 入口;容器部署示例以 Linux 服务器为目标。 | |
| 76 | 新增: | |
| 77 | 新增:## 协议接入 | |
| 78 | 新增: | |
| 79 | 新增:集成方通过 `POST /v1/rooms` 创建房间,将管理令牌放在 `Authorization: Bearer …` 请求头。返回值包含 `id`、`host_token`、`client_token`、`expires_at`,不得写入日志或公开页面。 | |
| 80 | 新增: | |
| 81 | 新增:主机与客户端分别访问 `GET /v1/rooms/{id}/host` 和 `GET /v1/rooms/{id}/client`,将各自房间令牌放在同一请求头中并升级到 WebSocket。接口不接受查询参数凭据。连接配对完成后进行端到端身份验证,再交换业务数据;房间地址本身也应视为敏感连接信息。 | |
| 82 | 新增: | |
| 83 | 新增:需要保存设备连接时,主机用 `lookup_hash` 登记设备专属查询凭据的摘要。手机把原查询凭据放在 Bearer 请求头中访问 `GET /v1/invitation`,取得主机已加入且尚未使用的房间邀请。断线后主机登记新房间,原查询凭据可以继续使用。中继重启后由在线主机重新登记。房间令牌和查询凭据分别管理,每次会话仍校验设备公钥。 | |
| 84 | 新增: | |
| 85 | 新增:中继不会转发 HTTP 路径到电脑上的管理服务。只有设备侧明确允许的应用操作才能进入 Cage。创建房间成功、WebSocket 成功和端到端握手成功分别代表不同阶段,调用方应保留对应错误反馈。 | |
| 86 | 新增: | |
| 87 | 新增:## 停止与更新 | |
| 88 | 新增: | |
| 89 | 新增:```sh | |
| 90 | 新增:docker compose -f deploy/relay/compose.yaml down | |
| 91 | 新增:docker compose -f deploy/relay/compose.yaml up -d --build | |
| 92 | 新增:``` | |
| 93 | 新增: | |
| 94 | 新增:停止服务会先关闭所有中继房间,再结束 HTTP 监听;两端需要重新连接。更新保留仓库外的令牌和 Caddy 证书卷。中继不访问电脑的 Cage 个人目录或虚拟机磁盘。 | |
| 95 | 新增: | |
| 96 | 新增:轮换管理令牌后需要重启中继;重启会清除全部房间。只修改管理令牌不能撤销设备间已经保存的信任关系,设备撤销必须由主机端授权层处理。执行更新时保留令牌文件权限,避免通过放宽文件权限解决读取失败。 | |
| @@ -0,0 +1,66 @@ | ||
| 1 | 新增:name: cage-relay | |
| 2 | 新增: | |
| 3 | 新增:services: | |
| 4 | 新增: relay: | |
| 5 | 新增: image: cage-relay:local | |
| 6 | 新增: build: | |
| 7 | 新增: context: ../.. | |
| 8 | 新增: dockerfile: deploy/relay/Dockerfile | |
| 9 | 新增: user: "${RELAY_UID:?Set RELAY_UID to the token file owner UID}:${RELAY_GID:?Set RELAY_GID to the token file owner GID}" | |
| 10 | 新增: command: | |
| 11 | 新增: - --listen=0.0.0.0:8787 | |
| 12 | 新增: - --token-file=/run/secrets/relay_admin_token | |
| 13 | 新增: - --max-rooms=128 | |
| 14 | 新增: - --pair-timeout=2m | |
| 15 | 新增: - --idle-timeout=5m | |
| 16 | 新增: secrets: | |
| 17 | 新增: - relay_admin_token | |
| 18 | 新增: networks: | |
| 19 | 新增: - backend | |
| 20 | 新增: read_only: true | |
| 21 | 新增: cap_drop: | |
| 22 | 新增: - ALL | |
| 23 | 新增: security_opt: | |
| 24 | 新增: - no-new-privileges:true | |
| 25 | 新增: stop_grace_period: 15s | |
| 26 | 新增: restart: unless-stopped | |
| 27 | 新增: | |
| 28 | 新增: caddy: | |
| 29 | 新增: image: caddy:2.11.8-alpine | |
| 30 | 新增: environment: | |
| 31 | 新增: RELAY_DOMAIN: "${RELAY_DOMAIN:?Set RELAY_DOMAIN to the relay public DNS name}" | |
| 32 | 新增: depends_on: | |
| 33 | 新增: - relay | |
| 34 | 新增: ports: | |
| 35 | 新增: - "80:80" | |
| 36 | 新增: - "443:443" | |
| 37 | 新增: volumes: | |
| 38 | 新增: - ./Caddyfile:/etc/caddy/Caddyfile:ro | |
| 39 | 新增: - caddy_data:/data | |
| 40 | 新增: - caddy_config:/config | |
| 41 | 新增: networks: | |
| 42 | 新增: - edge | |
| 43 | 新增: - backend | |
| 44 | 新增: read_only: true | |
| 45 | 新增: tmpfs: | |
| 46 | 新增: - /tmp | |
| 47 | 新增: cap_drop: | |
| 48 | 新增: - ALL | |
| 49 | 新增: cap_add: | |
| 50 | 新增: - NET_BIND_SERVICE | |
| 51 | 新增: security_opt: | |
| 52 | 新增: - no-new-privileges:true | |
| 53 | 新增: restart: unless-stopped | |
| 54 | 新增: | |
| 55 | 新增:secrets: | |
| 56 | 新增: relay_admin_token: | |
| 57 | 新增: file: "${RELAY_TOKEN_FILE:?Set RELAY_TOKEN_FILE to an absolute protected token file path}" | |
| 58 | 新增: | |
| 59 | 新增:networks: | |
| 60 | 新增: edge: {} | |
| 61 | 新增: backend: | |
| 62 | 新增: internal: true | |
| 63 | 新增: | |
| 64 | 新增:volumes: | |
| 65 | 新增: caddy_data: {} | |
| 66 | 新增: caddy_config: {} | |
| @@ -0,0 +1,118 @@ | ||
| 1 | 新增:package mobilelink | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "net" | |
| 9 | 新增: "net/http" | |
| 10 | 新增: "net/http/cookiejar" | |
| 11 | 新增: "net/url" | |
| 12 | 新增: "strconv" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "time" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:type Workbench struct { | |
| 18 | 新增: phoneRoom string | |
| 19 | 新增: origin string | |
| 20 | 新增: jar http.CookieJar | |
| 21 | 新增: transport *http.Transport | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:func loopback(host string) bool { | |
| 25 | 新增: ip := net.ParseIP(host) | |
| 26 | 新增: return host == "localhost" || ip != nil && ip.IsLoopback() | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:func explicitPort(u *url.URL) bool { | |
| 30 | 新增: port, err := strconv.Atoi(u.Port()) | |
| 31 | 新增: return err == nil && port >= 1 && port <= 65535 | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:// OpenWorkbench consumes a ticket issued by the trusted local cage server-entry | |
| 35 | 新增:// command. Only the host process ever sees the ticket and the resulting cookie. | |
| 36 | 新增:func OpenWorkbench(ctx context.Context, origin, ticket string) (*Workbench, error) { | |
| 37 | 新增: u, err := url.Parse(origin) | |
| 38 | 新增: if err != nil || u.Scheme != "http" || !loopback(u.Hostname()) || !explicitPort(u) || | |
| 39 | 新增: u.User != nil || u.Path != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || len(ticket) < 32 || len(ticket) > 512 { | |
| 40 | 新增: return nil, errors.New("invalid local Cage entry") | |
| 41 | 新增: } | |
| 42 | 新增: hostname := u.Hostname() | |
| 43 | 新增: if hostname == "localhost" { | |
| 44 | 新增: hostname = "127.0.0.1" | |
| 45 | 新增: } | |
| 46 | 新增: target := net.JoinHostPort(hostname, u.Port()) | |
| 47 | 新增: dialer := net.Dialer{Timeout: 5 * time.Second} | |
| 48 | 新增: transport := &http.Transport{Proxy: nil, MaxIdleConnsPerHost: 8, IdleConnTimeout: time.Minute, ResponseHeaderTimeout: 35 * time.Second, | |
| 49 | 新增: DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { | |
| 50 | 新增: if network != "tcp" || address != u.Host { | |
| 51 | 新增: return nil, errors.New("nonlocal upstream refused") | |
| 52 | 新增: } | |
| 53 | 新增: return dialer.DialContext(ctx, "tcp", target) | |
| 54 | 新增: }, | |
| 55 | 新增: } | |
| 56 | 新增: jar, _ := cookiejar.New(nil) | |
| 57 | 新增: b := &Workbench{origin: origin, transport: transport, jar: jar} | |
| 58 | 新增: payload, err := json.Marshal(map[string]string{"token": ticket}) | |
| 59 | 新增: if err != nil { | |
| 60 | 新增: return nil, errors.New("invalid entry ticket") | |
| 61 | 新增: } | |
| 62 | 新增: defer clear(payload) | |
| 63 | 新增: ctx, cancel := context.WithTimeout(ctx, 5*time.Second) | |
| 64 | 新增: defer cancel() | |
| 65 | 新增: req, err := http.NewRequestWithContext(ctx, http.MethodPost, origin+"/api/session", bytes.NewReader(payload)) | |
| 66 | 新增: if err != nil { | |
| 67 | 新增: return nil, errors.New("invalid local Cage origin") | |
| 68 | 新增: } | |
| 69 | 新增: req.GetBody = nil | |
| 70 | 新增: req.Header.Set("Content-Type", "application/json") | |
| 71 | 新增: req.Header.Set("Origin", origin) | |
| 72 | 新增: response, err := transport.RoundTrip(req) | |
| 73 | 新增: if err != nil { | |
| 74 | 新增: b.Close() | |
| 75 | 新增: return nil, errors.New("Cage entry ticket exchange failed") | |
| 76 | 新增: } | |
| 77 | 新增: response.Body.Close() | |
| 78 | 新增: if response.StatusCode == http.StatusOK { | |
| 79 | 新增: for _, cookie := range response.Cookies() { | |
| 80 | 新增: if cookie.Name == "cage_session_"+u.Port() && cookie.Value != "" { | |
| 81 | 新增: jar.SetCookies(u, []*http.Cookie{cookie}) | |
| 82 | 新增: } | |
| 83 | 新增: } | |
| 84 | 新增: } | |
| 85 | 新增: if len(jar.Cookies(u)) != 1 { | |
| 86 | 新增: b.Close() | |
| 87 | 新增: return nil, errors.New("Cage did not issue a valid local session cookie") | |
| 88 | 新增: } | |
| 89 | 新增: return b, nil | |
| 90 | 新增:} | |
| 91 | 新增: | |
| 92 | 新增:// SetPhoneRoom binds graphical and device metadata requests to this authenticated, UI-managed | |
| 93 | 新增:// pairing. The room proof is never accepted from the phone or sent to it. | |
| 94 | 新增:func (b *Workbench) SetPhoneRoom(proof string) { b.phoneRoom = proof } | |
| 95 | 新增: | |
| 96 | 新增:const PhoneRoomHeader = "X-Cage-Phone-Room" | |
| 97 | 新增: | |
| 98 | 新增:func (b *Workbench) Close() { b.transport.CloseIdleConnections() } | |
| 99 | 新增: | |
| 100 | 新增:// RoundTrip rebuilds requests in operations. This private transport receives | |
| 101 | 新增:// no caller-supplied headers and never follows redirects. | |
| 102 | 新增:type localTransport struct{ b *Workbench } | |
| 103 | 新增: | |
| 104 | 新增:func (t localTransport) RoundTrip(req *http.Request) (*http.Response, error) { | |
| 105 | 新增: if t.b.phoneRoom != "" && strings.HasPrefix(req.URL.Path, "/api/mobile/") { | |
| 106 | 新增: req.Header.Set(PhoneRoomHeader, t.b.phoneRoom) | |
| 107 | 新增: } | |
| 108 | 新增: for _, cookie := range t.b.jar.Cookies(req.URL) { | |
| 109 | 新增: req.AddCookie(cookie) | |
| 110 | 新增: } | |
| 111 | 新增: return t.b.transport.RoundTrip(req) | |
| 112 | 新增:} | |
| 113 | 新增: | |
| 114 | 新增:func (b *Workbench) handler() http.Handler { | |
| 115 | 新增: return operations(func(ctx context.Context, method, path string, body []byte) (*Reply, error) { | |
| 116 | 新增: return request(ctx, localTransport{b}, b.origin, method, path, body, true) | |
| 117 | 新增: }) | |
| 118 | 新增:} | |
| @@ -0,0 +1,150 @@ | ||
| 1 | 新增:package mobilelink | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "crypto/rand" | |
| 6 | 新增: "crypto/sha256" | |
| 7 | 新增: "crypto/subtle" | |
| 8 | 新增: "encoding/base64" | |
| 9 | 新增: "encoding/json" | |
| 10 | 新增: "errors" | |
| 11 | 新增: "io/fs" | |
| 12 | 新增: "net/http" | |
| 13 | 新增: "net/url" | |
| 14 | 新增: "os" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "sync" | |
| 17 | 新增: "time" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:const bootstrapJS = `(async()=>{try { | |
| 21 | 新增: const destination=new URLSearchParams(location.search).get("page")==="archived"?"/?page=archived":"/"; | |
| 22 | 新增: const token=location.hash.slice(1); history.replaceState(null,"",location.pathname); | |
| 23 | 新增: const res=await fetch("/link-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token})}); | |
| 24 | 新增: if (!res.ok) throw Error(); location.replace(destination); | |
| 25 | 新增:}catch{document.body.textContent="连接入口已失效,请使用本机新生成的入口。";}})();` | |
| 26 | 新增: | |
| 27 | 新增:type Browser struct { | |
| 28 | 新增: mu sync.Mutex | |
| 29 | 新增: origin *url.URL | |
| 30 | 新增: launch [32]byte | |
| 31 | 新增: launchTTL time.Time | |
| 32 | 新增: cookie string | |
| 33 | 新增: root *os.Root | |
| 34 | 新增: api http.Handler | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:func randomToken() string { | |
| 38 | 新增: b := make([]byte, 32) | |
| 39 | 新增: _, _ = rand.Read(b) | |
| 40 | 新增: return base64.RawURLEncoding.EncodeToString(b) | |
| 41 | 新增:} | |
| 42 | 新增: | |
| 43 | 新增:type OperationClient interface { | |
| 44 | 新增: Do(context.Context, string, string, []byte) (*Reply, error) | |
| 45 | 新增:} | |
| 46 | 新增: | |
| 47 | 新增:// NewBrowser serves trusted mobile build assets and the restricted client | |
| 48 | 新增:// bridge on an explicitly loopback-only listener. The caller places launchURL | |
| 49 | 新增:// into a private local launch file. It must never be printed or logged. | |
| 50 | 新增:func NewBrowser(origin, directory string, client OperationClient) (browser *Browser, launchURL string, err error) { | |
| 51 | 新增: u, err := url.Parse(origin) | |
| 52 | 新增: if err != nil || u.Scheme != "http" || !loopback(u.Hostname()) || !explicitPort(u) || u.User != nil || | |
| 53 | 新增: u.Path != "" || u.Fragment != "" || u.RawQuery != "" || u.ForceQuery || client == nil { | |
| 54 | 新增: return nil, "", errors.New("local UI requires a loopback origin and a connected peer") | |
| 55 | 新增: } | |
| 56 | 新增: root, err := os.OpenRoot(directory) | |
| 57 | 新增: if err != nil { | |
| 58 | 新增: return nil, "", errors.New("cannot open local mobile build directory") | |
| 59 | 新增: } | |
| 60 | 新增: if info, err := root.Stat("mobile.html"); err != nil || !info.Mode().IsRegular() { | |
| 61 | 新增: root.Close() | |
| 62 | 新增: return nil, "", errors.New("build directory must contain mobile.html") | |
| 63 | 新增: } | |
| 64 | 新增: token := randomToken() | |
| 65 | 新增: b := &Browser{origin: u, root: root, api: operations(client.Do), launch: sha256.Sum256([]byte(token)), launchTTL: time.Now().Add(2 * time.Minute), cookie: randomToken()} | |
| 66 | 新增: return b, origin + "/link-bootstrap#" + token, nil | |
| 67 | 新增:} | |
| 68 | 新增: | |
| 69 | 新增:func (b *Browser) Close() error { return b.root.Close() } | |
| 70 | 新增: | |
| 71 | 新增:func (b *Browser) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
| 72 | 新增: w.Header().Set("Cache-Control", "no-store") | |
| 73 | 新增: w.Header().Set("Referrer-Policy", "no-referrer") | |
| 74 | 新增: w.Header().Set("X-Content-Type-Options", "nosniff") | |
| 75 | 新增: w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'") | |
| 76 | 新增: if r.Host != b.origin.Host || (r.Header.Get("Origin") != "" && r.Header.Get("Origin") != b.origin.String()) || | |
| 77 | 新增: (r.Method != http.MethodGet && r.Header.Get("Origin") != b.origin.String()) || r.URL.RawPath != "" { | |
| 78 | 新增: http.Error(w, "origin refused", http.StatusForbidden) | |
| 79 | 新增: return | |
| 80 | 新增: } | |
| 81 | 新增: if r.Method == http.MethodGet && (r.URL.RawQuery == "" || (r.URL.Path == "/link-bootstrap" && r.URL.RawQuery == "page=archived")) { | |
| 82 | 新增: switch r.URL.Path { | |
| 83 | 新增: case "/link-bootstrap": | |
| 84 | 新增: w.Header().Set("Content-Type", "text/html; charset=utf-8") | |
| 85 | 新增: _, _ = w.Write([]byte(`<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>Cage</title><body>正在连接 Cage…<script src="/link-bootstrap.js"></script></body></html>`)) | |
| 86 | 新增: return | |
| 87 | 新增: case "/link-bootstrap.js": | |
| 88 | 新增: w.Header().Set("Content-Type", "text/javascript; charset=utf-8") | |
| 89 | 新增: _, _ = w.Write([]byte(bootstrapJS)) | |
| 90 | 新增: return | |
| 91 | 新增: } | |
| 92 | 新增: } | |
| 93 | 新增: name := "cage_mobile_link_" + b.origin.Port() | |
| 94 | 新增: if r.Method == http.MethodPost && r.URL.Path == "/link-session" && r.URL.RawQuery == "" { | |
| 95 | 新增: var in struct{ Token string } | |
| 96 | 新增: data, err := limited(r.Body, 512) | |
| 97 | 新增: if err != nil || json.Unmarshal(data, &in) != nil { | |
| 98 | 新增: http.Error(w, "invalid entry", http.StatusBadRequest) | |
| 99 | 新增: return | |
| 100 | 新增: } | |
| 101 | 新增: digest := sha256.Sum256([]byte(in.Token)) | |
| 102 | 新增: b.mu.Lock() | |
| 103 | 新增: valid := time.Now().Before(b.launchTTL) && subtle.ConstantTimeCompare(digest[:], b.launch[:]) == 1 | |
| 104 | 新增: if valid { | |
| 105 | 新增: b.launchTTL = time.Time{} | |
| 106 | 新增: clear(b.launch[:]) | |
| 107 | 新增: } | |
| 108 | 新增: b.mu.Unlock() | |
| 109 | 新增: if !valid { | |
| 110 | 新增: http.Error(w, "entry expired", http.StatusUnauthorized) | |
| 111 | 新增: return | |
| 112 | 新增: } | |
| 113 | 新增: http.SetCookie(w, &http.Cookie{Name: name, Value: b.cookie, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode}) | |
| 114 | 新增: w.WriteHeader(http.StatusNoContent) | |
| 115 | 新增: return | |
| 116 | 新增: } | |
| 117 | 新增: cookie, err := r.Cookie(name) | |
| 118 | 新增: if err != nil || subtle.ConstantTimeCompare([]byte(cookie.Value), []byte(b.cookie)) != 1 { | |
| 119 | 新增: http.Error(w, "open the private local launch file", http.StatusUnauthorized) | |
| 120 | 新增: return | |
| 121 | 新增: } | |
| 122 | 新增: if strings.HasPrefix(r.URL.Path, "/api/") { | |
| 123 | 新增: b.api.ServeHTTP(w, r) | |
| 124 | 新增: return | |
| 125 | 新增: } | |
| 126 | 新增: if r.Method != http.MethodGet { | |
| 127 | 新增: http.NotFound(w, r) | |
| 128 | 新增: return | |
| 129 | 新增: } | |
| 130 | 新增: file := strings.TrimPrefix(r.URL.Path, "/") | |
| 131 | 新增: if file == "" { | |
| 132 | 新增: file = "mobile.html" | |
| 133 | 新增: } | |
| 134 | 新增: if (file != "mobile.html" && !strings.HasPrefix(file, "assets/")) || !fs.ValidPath(file) || strings.Contains(file, "\\") { | |
| 135 | 新增: http.NotFound(w, r) | |
| 136 | 新增: return | |
| 137 | 新增: } | |
| 138 | 新增: f, err := b.root.Open(file) | |
| 139 | 新增: if err != nil { | |
| 140 | 新增: http.NotFound(w, r) | |
| 141 | 新增: return | |
| 142 | 新增: } | |
| 143 | 新增: defer f.Close() | |
| 144 | 新增: info, err := f.Stat() | |
| 145 | 新增: if err != nil || !info.Mode().IsRegular() { | |
| 146 | 新增: http.NotFound(w, r) | |
| 147 | 新增: return | |
| 148 | 新增: } | |
| 149 | 新增: http.ServeContent(w, r, info.Name(), info.ModTime(), f) | |
| 150 | 新增:} | |
| @@ -0,0 +1,38 @@ | ||
| 1 | 新增:package mobilelink | |
| 2 | 新增: | |
| 3 | 新增:import "strings" | |
| 4 | 新增: | |
| 5 | 新增:// DeviceInfo is descriptive metadata. Device trust continues to use the pinned key. | |
| 6 | 新增:type DeviceInfo struct { | |
| 7 | 新增: Platform string `json:"platform"` | |
| 8 | 新增: Model string `json:"model"` | |
| 9 | 新增:} | |
| 10 | 新增: | |
| 11 | 新增:// iOS exposes a hardware identifier rather than the retail model name. | |
| 12 | 新增:// Identifier reference: https://github.com/devicekit/DeviceKit/blob/master/Source/Device.generated.swift | |
| 13 | 新增:var iphoneModels = map[string]string{ | |
| 14 | 新增: "iPhone11,2": "iPhone XS", "iPhone11,4": "iPhone XS Max", "iPhone11,6": "iPhone XS Max", "iPhone11,8": "iPhone XR", | |
| 15 | 新增: "iPhone12,1": "iPhone 11", "iPhone12,3": "iPhone 11 Pro", "iPhone12,5": "iPhone 11 Pro Max", "iPhone12,8": "iPhone SE (第 2 代)", | |
| 16 | 新增: "iPhone13,1": "iPhone 12 mini", "iPhone13,2": "iPhone 12", "iPhone13,3": "iPhone 12 Pro", "iPhone13,4": "iPhone 12 Pro Max", | |
| 17 | 新增: "iPhone14,2": "iPhone 13 Pro", "iPhone14,3": "iPhone 13 Pro Max", "iPhone14,4": "iPhone 13 mini", "iPhone14,5": "iPhone 13", "iPhone14,6": "iPhone SE (第 3 代)", | |
| 18 | 新增: "iPhone14,7": "iPhone 14", "iPhone14,8": "iPhone 14 Plus", "iPhone15,2": "iPhone 14 Pro", "iPhone15,3": "iPhone 14 Pro Max", | |
| 19 | 新增: "iPhone15,4": "iPhone 15", "iPhone15,5": "iPhone 15 Plus", "iPhone16,1": "iPhone 15 Pro", "iPhone16,2": "iPhone 15 Pro Max", | |
| 20 | 新增: "iPhone17,1": "iPhone 16 Pro", "iPhone17,2": "iPhone 16 Pro Max", "iPhone17,3": "iPhone 16", "iPhone17,4": "iPhone 16 Plus", "iPhone17,5": "iPhone 16e", | |
| 21 | 新增: "iPhone18,1": "iPhone 17 Pro", "iPhone18,2": "iPhone 17 Pro Max", "iPhone18,3": "iPhone 17", "iPhone18,4": "iPhone Air", "iPhone18,5": "iPhone 17e", | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:func DeviceModel(platform, model string) string { | |
| 25 | 新增: model = strings.TrimSpace(model) | |
| 26 | 新增: if platform == "ios" { | |
| 27 | 新增: if name := iphoneModels[model]; name != "" { | |
| 28 | 新增: return name | |
| 29 | 新增: } | |
| 30 | 新增: if strings.HasPrefix(model, "iPhone") { | |
| 31 | 新增: return "iPhone (" + model + ")" | |
| 32 | 新增: } | |
| 33 | 新增: if strings.HasPrefix(model, "iPad") { | |
| 34 | 新增: return "iPad (" + model + ")" | |
| 35 | 新增: } | |
| 36 | 新增: } | |
| 37 | 新增: return model | |
| 38 | 新增:} | |
| @@ -0,0 +1,31 @@ | ||
| 1 | 新增:package mobilelink | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "net/url" | |
| 5 | 新增: "testing" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:func TestDeviceModel(t *testing.T) { | |
| 9 | 新增: for _, tc := range []struct{ platform, raw, want string }{ | |
| 10 | 新增: {"ios", "iPhone17,1", "iPhone 16 Pro"}, | |
| 11 | 新增: {"ios", "iPhone18,1", "iPhone 17 Pro"}, | |
| 12 | 新增: {"ios", "iPhone99,1", "iPhone (iPhone99,1)"}, | |
| 13 | 新增: {"ios", "iPad99,1", "iPad (iPad99,1)"}, | |
| 14 | 新增: {"android", " Google Pixel 9 Pro ", "Google Pixel 9 Pro"}, | |
| 15 | 新增: } { | |
| 16 | 新增: if got := DeviceModel(tc.platform, tc.raw); got != tc.want { | |
| 17 | 新增: t.Errorf("%s %q: got %q, want %q", tc.platform, tc.raw, got, tc.want) | |
| 18 | 新增: } | |
| 19 | 新增: } | |
| 20 | 新增:} | |
| 21 | 新增: | |
| 22 | 新增:func TestDeviceReportOperationBoundary(t *testing.T) { | |
| 23 | 新增: u := &url.URL{Path: "/api/mobile/device"} | |
| 24 | 新增: if !allowed("POST", u) || allowed("GET", u) || allowed("DELETE", u) { | |
| 25 | 新增: t.Fatal("device report must only accept POST") | |
| 26 | 新增: } | |
| 27 | 新增: u.RawQuery = "model=other" | |
| 28 | 新增: if allowed("POST", u) { | |
| 29 | 新增: t.Fatal("device report must not accept query parameters") | |
| 30 | 新增: } | |
| 31 | 新增:} | |
| @@ -0,0 +1,277 @@ | ||
| 1 | 新增:package mobilelink | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/sha256" | |
| 7 | 新增: "crypto/tls" | |
| 8 | 新增: "encoding/base64" | |
| 9 | 新增: "encoding/hex" | |
| 10 | 新增: "encoding/json" | |
| 11 | 新增: "errors" | |
| 12 | 新增: "fmt" | |
| 13 | 新增: "io" | |
| 14 | 新增: "log" | |
| 15 | 新增: "net/http" | |
| 16 | 新增: "net/url" | |
| 17 | 新增: "strings" | |
| 18 | 新增: "time" | |
| 19 | 新增: | |
| 20 | 新增: "github.com/gorilla/websocket" | |
| 21 | 新增: "github.com/sylvinus/agent-vm/internal/relay" | |
| 22 | 新增: "github.com/sylvinus/agent-vm/internal/remotelink" | |
| 23 | 新增: "golang.org/x/net/http2" | |
| 24 | 新增:) | |
| 25 | 新增: | |
| 26 | 新增:const OfficialRelay = "https://43.142.88.90" | |
| 27 | 新增: | |
| 28 | 新增:func relayOrigin(base string) (*url.URL, error) { | |
| 29 | 新增: u, err := url.Parse(base) | |
| 30 | 新增: if err != nil || u.Hostname() == "" || u.User != nil || u.Path != "" || | |
| 31 | 新增: u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || | |
| 32 | 新增: (u.Scheme != "https" && (u.Scheme != "http" || !loopback(u.Hostname()))) { | |
| 33 | 新增: return nil, errors.New("relay must use an HTTPS origin or a local loopback HTTP origin") | |
| 34 | 新增: } | |
| 35 | 新增: return u, nil | |
| 36 | 新增:} | |
| 37 | 新增: | |
| 38 | 新增:func validCapability(value string) bool { | |
| 39 | 新增: b, err := base64.RawURLEncoding.DecodeString(value) | |
| 40 | 新增: return err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == value | |
| 41 | 新增:} | |
| 42 | 新增: | |
| 43 | 新增:// ValidRelayOrigin verifies the address before saving device configuration. | |
| 44 | 新增:func ValidRelayOrigin(base string) bool { | |
| 45 | 新增: _, err := relayOrigin(base) | |
| 46 | 新增: return err == nil | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 49 | 新增:// Retryable reports whether the host may establish a new transport room. | |
| 50 | 新增:// It never authorizes retrying an application request. | |
| 51 | 新增:type retryableError struct{ error } | |
| 52 | 新增: | |
| 53 | 新增:// ErrNoInvitation covers offline, occupied, and unknown pairings equally. | |
| 54 | 新增:var ErrNoInvitation = errors.New("no available room for the saved device") | |
| 55 | 新增: | |
| 56 | 新增:func Retryable(err error) bool { | |
| 57 | 新增: var transient retryableError | |
| 58 | 新增: return errors.As(err, &transient) | |
| 59 | 新增:} | |
| 60 | 新增: | |
| 61 | 新增:func relayNetworkError(ctx context.Context, err error) error { | |
| 62 | 新增: if ctx.Err() != nil { | |
| 63 | 新增: if errors.Is(ctx.Err(), context.DeadlineExceeded) { | |
| 64 | 新增: return retryableError{errors.New("relay request timed out")} | |
| 65 | 新增: } | |
| 66 | 新增: return ctx.Err() | |
| 67 | 新增: } | |
| 68 | 新增: var trust *tls.CertificateVerificationError | |
| 69 | 新增: if errors.As(err, &trust) { | |
| 70 | 新增: return errors.New("relay HTTPS certificate verification failed") | |
| 71 | 新增: } | |
| 72 | 新增: return retryableError{errors.New("could not connect to relay")} | |
| 73 | 新增:} | |
| 74 | 新增: | |
| 75 | 新增:func relayHTTPError(status int, missingIsTransient bool) error { | |
| 76 | 新增: err := fmt.Errorf("relay returned HTTP %d", status) | |
| 77 | 新增: if status == http.StatusConflict || status == http.StatusTooManyRequests || status == http.StatusRequestTimeout || | |
| 78 | 新增: status >= 500 || (missingIsTransient && status == http.StatusNotFound) { | |
| 79 | 新增: return retryableError{err} | |
| 80 | 新增: } | |
| 81 | 新增: return err | |
| 82 | 新增:} | |
| 83 | 新增: | |
| 84 | 新增:type ClientInvitation struct { | |
| 85 | 新增: ID string `json:"id"` | |
| 86 | 新增: ClientToken string `json:"client_token"` | |
| 87 | 新增: ExpiresAt time.Time `json:"expires_at"` | |
| 88 | 新增:} | |
| 89 | 新增: | |
| 90 | 新增:func relayRequest(ctx context.Context, base, method, path, token string, payload []byte, want int) ([]byte, error) { | |
| 91 | 新增: if _, err := relayOrigin(base); err != nil { | |
| 92 | 新增: return nil, err | |
| 93 | 新增: } | |
| 94 | 新增: ctx, cancel := context.WithTimeout(ctx, 10*time.Second) | |
| 95 | 新增: defer cancel() | |
| 96 | 新增: req, err := http.NewRequestWithContext(ctx, method, base+path, bytes.NewReader(payload)) | |
| 97 | 新增: if err != nil { | |
| 98 | 新增: return nil, errors.New("invalid relay origin") | |
| 99 | 新增: } | |
| 100 | 新增: req.GetBody = nil | |
| 101 | 新增: if token != "" { | |
| 102 | 新增: req.Header.Set("Authorization", "Bearer "+token) | |
| 103 | 新增: } | |
| 104 | 新增: if len(payload) != 0 { | |
| 105 | 新增: req.Header.Set("Content-Type", "application/json") | |
| 106 | 新增: } | |
| 107 | 新增: transport := &http.Transport{Proxy: nil, DisableKeepAlives: true} | |
| 108 | 新增: defer transport.CloseIdleConnections() | |
| 109 | 新增: res, err := transport.RoundTrip(req) | |
| 110 | 新增: if err != nil { | |
| 111 | 新增: return nil, relayNetworkError(ctx, err) | |
| 112 | 新增: } | |
| 113 | 新增: defer res.Body.Close() | |
| 114 | 新增: if res.StatusCode != want { | |
| 115 | 新增: if path == "/v1/invitation" && res.StatusCode == http.StatusNotFound { | |
| 116 | 新增: return nil, ErrNoInvitation | |
| 117 | 新增: } | |
| 118 | 新增: return nil, relayHTTPError(res.StatusCode, path == "/v1/invitation") | |
| 119 | 新增: } | |
| 120 | 新增: return limited(res.Body, 4096) | |
| 121 | 新增:} | |
| 122 | 新增: | |
| 123 | 新增:// CreateRoom exchanges the relay administrator token for two transport roles. | |
| 124 | 新增:// The host keeps the admin and host tokens. Only the client role is exported. | |
| 125 | 新增:func CreateRoom(ctx context.Context, base, admin string) (relay.Invitation, error) { | |
| 126 | 新增: return createRoom(ctx, base, admin, nil) | |
| 127 | 新增:} | |
| 128 | 新增: | |
| 129 | 新增:// CreateDiscoverableRoom registers a hash, never the long-lived lookup bearer. | |
| 130 | 新增:// A currently paired room cannot be displaced by a second registration. | |
| 131 | 新增:func CreateDiscoverableRoom(ctx context.Context, base, admin, lookupToken string) (relay.Invitation, error) { | |
| 132 | 新增: if !validCapability(lookupToken) { | |
| 133 | 新增: return relay.Invitation{}, errors.New("invalid saved connection token") | |
| 134 | 新增: } | |
| 135 | 新增: raw, _ := base64.RawURLEncoding.DecodeString(lookupToken) | |
| 136 | 新增: digest := sha256.Sum256(raw) | |
| 137 | 新增: clear(raw) | |
| 138 | 新增: payload, _ := json.Marshal(map[string]string{"lookup_hash": hex.EncodeToString(digest[:])}) | |
| 139 | 新增: return createRoom(ctx, base, admin, payload) | |
| 140 | 新增:} | |
| 141 | 新增: | |
| 142 | 新增:func createRoom(ctx context.Context, base, admin string, payload []byte) (relay.Invitation, error) { | |
| 143 | 新增: var invite relay.Invitation | |
| 144 | 新增: if (admin != "" && len(admin) < 32) || len(admin) > 4096 || strings.ContainsAny(admin, " \t\r\n") { | |
| 145 | 新增: return invite, errors.New("invalid relay administration token") | |
| 146 | 新增: } | |
| 147 | 新增: data, err := relayRequest(ctx, base, http.MethodPost, "/v1/rooms", admin, payload, http.StatusCreated) | |
| 148 | 新增: if err != nil { | |
| 149 | 新增: return invite, err | |
| 150 | 新增: } | |
| 151 | 新增: defer clear(data) | |
| 152 | 新增: if err != nil || json.Unmarshal(data, &invite) != nil || !validCapability(invite.ID) || | |
| 153 | 新增: !validCapability(invite.HostToken) || !validCapability(invite.ClientToken) || !invite.ExpiresAt.After(time.Now()) { | |
| 154 | 新增: return relay.Invitation{}, errors.New("invalid relay invitation") | |
| 155 | 新增: } | |
| 156 | 新增: return invite, nil | |
| 157 | 新增:} | |
| 158 | 新增: | |
| 159 | 新增:// LookupRoom retrieves the current one-use client role for a saved pairing. | |
| 160 | 新增:// The host fingerprint is supplied independently to ConnectClient. | |
| 161 | 新增:func LookupRoom(ctx context.Context, base, lookupToken string) (ClientInvitation, error) { | |
| 162 | 新增: var room ClientInvitation | |
| 163 | 新增: if !validCapability(lookupToken) { | |
| 164 | 新增: return room, errors.New("invalid saved connection token") | |
| 165 | 新增: } | |
| 166 | 新增: data, err := relayRequest(ctx, base, http.MethodGet, "/v1/invitation", lookupToken, nil, http.StatusOK) | |
| 167 | 新增: if err != nil { | |
| 168 | 新增: return room, err | |
| 169 | 新增: } | |
| 170 | 新增: defer clear(data) | |
| 171 | 新增: dec := json.NewDecoder(bytes.NewReader(data)) | |
| 172 | 新增: dec.DisallowUnknownFields() | |
| 173 | 新增: if dec.Decode(&room) != nil || dec.Decode(new(any)) != io.EOF || !validCapability(room.ID) || !validCapability(room.ClientToken) || !room.ExpiresAt.After(time.Now()) { | |
| 174 | 新增: return ClientInvitation{}, errors.New("invalid saved connection invitation") | |
| 175 | 新增: } | |
| 176 | 新增: return room, nil | |
| 177 | 新增:} | |
| 178 | 新增: | |
| 179 | 新增:func join(ctx context.Context, base, roomID, role, token string) (*websocket.Conn, error) { | |
| 180 | 新增: u, err := relayOrigin(base) | |
| 181 | 新增: if err != nil { | |
| 182 | 新增: return nil, err | |
| 183 | 新增: } | |
| 184 | 新增: if !validCapability(roomID) || !validCapability(token) { | |
| 185 | 新增: return nil, errors.New("invalid relay room credentials") | |
| 186 | 新增: } | |
| 187 | 新增: if u.Scheme == "https" { | |
| 188 | 新增: u.Scheme = "wss" | |
| 189 | 新增: } else { | |
| 190 | 新增: u.Scheme = "ws" | |
| 191 | 新增: } | |
| 192 | 新增: u.Path = "/v1/rooms/" + roomID + "/" + role | |
| 193 | 新增: dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second} | |
| 194 | 新增: socket, res, err := dialer.DialContext(ctx, u.String(), http.Header{"Authorization": {"Bearer " + token}}) | |
| 195 | 新增: if err != nil { | |
| 196 | 新增: if res != nil { | |
| 197 | 新增: res.Body.Close() | |
| 198 | 新增: return nil, relayHTTPError(res.StatusCode, true) | |
| 199 | 新增: } | |
| 200 | 新增: return nil, relayNetworkError(ctx, err) | |
| 201 | 新增: } | |
| 202 | 新增: return socket, nil | |
| 203 | 新增:} | |
| 204 | 新增: | |
| 205 | 新增:// ServeHost waits for an authenticated device and serves this workbench only. | |
| 206 | 新增:// All requests pass the canonical mobile route filter and local Cage gates. | |
| 207 | 新增:func ServeHost(ctx context.Context, base, roomID, hostToken string, identity *remotelink.Identity, expectedPin string, b *Workbench) error { | |
| 208 | 新增: if b == nil { | |
| 209 | 新增: return errors.New("local workbench session required") | |
| 210 | 新增: } | |
| 211 | 新增: ws, err := join(ctx, base, roomID, "host", hostToken) | |
| 212 | 新增: if err != nil { | |
| 213 | 新增: return err | |
| 214 | 新增: } | |
| 215 | 新增: conn, err := remotelink.ServerAfterJoin(ctx, ws, identity, expectedPin) | |
| 216 | 新增: if err != nil { | |
| 217 | 新增: if ctx.Err() != nil { | |
| 218 | 新增: return ctx.Err() | |
| 219 | 新增: } | |
| 220 | 新增: return retryableError{errors.New("room expired, disconnected, or peer authentication failed")} | |
| 221 | 新增: } | |
| 222 | 新增: stop := context.AfterFunc(ctx, func() { _ = conn.NetConn().Close() }) | |
| 223 | 新增: defer stop() | |
| 224 | 新增: defer conn.NetConn().Close() | |
| 225 | 新增: hostHandler := b.handler() | |
| 226 | 新增: server := &http2.Server{MaxConcurrentStreams: 16} | |
| 227 | 新增: server.ServeConn(conn, &http2.ServeConnOpts{Context: ctx, BaseConfig: &http.Server{ | |
| 228 | 新增: MaxHeaderBytes: 16 << 10, IdleTimeout: 5 * time.Minute, ErrorLog: log.New(io.Discard, "", 0), | |
| 229 | 新增: }, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 230 | 新增: if r.Host != "cage-mobile.invalid" { | |
| 231 | 新增: http.Error(w, "invalid mobile authority", http.StatusForbidden) | |
| 232 | 新增: return | |
| 233 | 新增: } | |
| 234 | 新增: hostHandler.ServeHTTP(w, r) | |
| 235 | 新增: })}) | |
| 236 | 新增: return ctx.Err() | |
| 237 | 新增:} | |
| 238 | 新增: | |
| 239 | 新增:type Client struct { | |
| 240 | 新增: session *http2.ClientConn | |
| 241 | 新增: conn *tls.Conn | |
| 242 | 新增:} | |
| 243 | 新增: | |
| 244 | 新增:// ConnectClient opens a single authenticated HTTP/2 connection. expectedPin | |
| 245 | 新增:// must come from an independently verified trust record on this device. | |
| 246 | 新增:func ConnectClient(ctx context.Context, base, roomID, clientToken string, identity *remotelink.Identity, expectedPin string) (*Client, error) { | |
| 247 | 新增: ws, err := join(ctx, base, roomID, "client", clientToken) | |
| 248 | 新增: if err != nil { | |
| 249 | 新增: return nil, err | |
| 250 | 新增: } | |
| 251 | 新增: conn, err := remotelink.Client(ctx, ws, identity, expectedPin) | |
| 252 | 新增: if err != nil { | |
| 253 | 新增: return nil, errors.New("paired host authentication failed") | |
| 254 | 新增: } | |
| 255 | 新增: transport := &http2.Transport{MaxHeaderListSize: 16 << 10, ReadIdleTimeout: 15 * time.Second, PingTimeout: 8 * time.Second} | |
| 256 | 新增: session, err := transport.NewClientConn(conn) | |
| 257 | 新增: if err != nil { | |
| 258 | 新增: conn.NetConn().Close() | |
| 259 | 新增: return nil, errors.New("mobile protocol initialization failed") | |
| 260 | 新增: } | |
| 261 | 新增: return &Client{session: session, conn: conn}, nil | |
| 262 | 新增:} | |
| 263 | 新增: | |
| 264 | 新增:func (c *Client) Do(ctx context.Context, method, path string, body []byte) (*Reply, error) { | |
| 265 | 新增: return request(ctx, c.session, linkOrigin, method, path, body, false) | |
| 266 | 新增:} | |
| 267 | 新增: | |
| 268 | 新增:// Disconnected reports a retired transport, including a peer that sent GOAWAY. | |
| 269 | 新增:func (c *Client) Disconnected() bool { | |
| 270 | 新增: state := c.session.State() | |
| 271 | 新增: return state.Closed || state.Closing | |
| 272 | 新增:} | |
| 273 | 新增: | |
| 274 | 新增:func (c *Client) Close() error { | |
| 275 | 新增: _ = c.conn.NetConn().Close() | |
| 276 | 新增: return c.session.Close() | |
| 277 | 新增:} | |
| @@ -0,0 +1,535 @@ | ||
| 1 | 新增:package mobilelink_test | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/ecdsa" | |
| 7 | 新增: "crypto/elliptic" | |
| 8 | 新增: "crypto/rand" | |
| 9 | 新增: "crypto/x509" | |
| 10 | 新增: "encoding/json" | |
| 11 | 新增: "fmt" | |
| 12 | 新增: "io" | |
| 13 | 新增: "net" | |
| 14 | 新增: "net/http" | |
| 15 | 新增: "net/http/httptest" | |
| 16 | 新增: "net/url" | |
| 17 | 新增: "os" | |
| 18 | 新增: "path/filepath" | |
| 19 | 新增: "strings" | |
| 20 | 新增: "sync/atomic" | |
| 21 | 新增: "testing" | |
| 22 | 新增: "time" | |
| 23 | 新增: | |
| 24 | 新增: "github.com/gorilla/websocket" | |
| 25 | 新增: "github.com/sylvinus/agent-vm/internal/mobilelink" | |
| 26 | 新增: "github.com/sylvinus/agent-vm/internal/mobilelink/nativeclient" | |
| 27 | 新增: "github.com/sylvinus/agent-vm/internal/relay" | |
| 28 | 新增: "github.com/sylvinus/agent-vm/internal/remotelink" | |
| 29 | 新增: "golang.org/x/net/http2" | |
| 30 | 新增:) | |
| 31 | 新增: | |
| 32 | 新增:type device struct{ key *ecdsa.PrivateKey } | |
| 33 | 新增: | |
| 34 | 新增:func (d device) PublicKeyDER() ([]byte, error) { return x509.MarshalPKIXPublicKey(&d.key.PublicKey) } | |
| 35 | 新增:func (d device) SignSHA256(hash []byte) ([]byte, error) { | |
| 36 | 新增: return ecdsa.SignASN1(rand.Reader, d.key, hash) | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:const session = "/api/mobile/cli/sessions/12345678-1234-4321-aaaa-123456789abc" | |
| 40 | 新增: | |
| 41 | 新增:type fixture struct { | |
| 42 | 新增: base string | |
| 43 | 新增: backend *mobilelink.Workbench | |
| 44 | 新增: identity *remotelink.Identity | |
| 45 | 新增: locked atomic.Bool | |
| 46 | 新增: upstream atomic.Int32 | |
| 47 | 新增: activeGet chan struct{} | |
| 48 | 新增: finishGet chan struct{} | |
| 49 | 新增:} | |
| 50 | 新增: | |
| 51 | 新增:func newFixture(t *testing.T) *fixture { | |
| 52 | 新增: t.Helper() | |
| 53 | 新增: f := &fixture{activeGet: make(chan struct{}, 1), finishGet: make(chan struct{})} | |
| 54 | 新增: id, err := remotelink.NewIdentity() | |
| 55 | 新增: if err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: f.identity = id | |
| 59 | 新增: ticket := strings.Repeat("test-ticket-", 5) | |
| 60 | 新增: const cookie = "local-cookie-must-stay-on-host" | |
| 61 | 新增: control := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 62 | 新增: if r.Header.Get("Origin") != "http://"+r.Host { | |
| 63 | 新增: http.Error(w, "origin refused", 403) | |
| 64 | 新增: return | |
| 65 | 新增: } | |
| 66 | 新增: _, port, _ := net.SplitHostPort(r.Host) | |
| 67 | 新增: name := "cage_session_" + port | |
| 68 | 新增: if r.URL.Path == "/api/session" { | |
| 69 | 新增: var in struct{ Token string } | |
| 70 | 新增: if r.Method != http.MethodPost || json.NewDecoder(r.Body).Decode(&in) != nil || in.Token != ticket { | |
| 71 | 新增: http.Error(w, "ticket refused", 401) | |
| 72 | 新增: return | |
| 73 | 新增: } | |
| 74 | 新增: http.SetCookie(w, &http.Cookie{Name: name, Value: cookie, Path: "/", HttpOnly: true}) | |
| 75 | 新增: return | |
| 76 | 新增: } | |
| 77 | 新增: c, err := r.Cookie(name) | |
| 78 | 新增: if err != nil || c.Value != cookie || len(r.Cookies()) != 1 || r.Header.Get("Authorization") != "" { | |
| 79 | 新增: http.Error(w, "session refused", 401) | |
| 80 | 新增: return | |
| 81 | 新增: } | |
| 82 | 新增: f.upstream.Add(1) | |
| 83 | 新增: if f.locked.Load() { | |
| 84 | 新增: http.Error(w, "locked", 423) | |
| 85 | 新增: return | |
| 86 | 新增: } | |
| 87 | 新增: w.Header().Set("Content-Type", "application/json") | |
| 88 | 新增: switch { | |
| 89 | 新增: case r.URL.Path == "/api/mobile/cli/projects": | |
| 90 | 新增: _, _ = io.WriteString(w, `{"projects":["B"]}`) | |
| 91 | 新增: case r.URL.Path == session && r.URL.RawQuery == "after=2": | |
| 92 | 新增: f.activeGet <- struct{}{} | |
| 93 | 新增: select { | |
| 94 | 新增: case <-f.finishGet: | |
| 95 | 新增: w.WriteHeader(204) | |
| 96 | 新增: case <-r.Context().Done(): | |
| 97 | 新增: } | |
| 98 | 新增: case (r.URL.Path == session+"/messages" || r.URL.Path == session+"/approval") && r.Method == http.MethodPost: | |
| 99 | 新增: data, _ := io.ReadAll(r.Body) | |
| 100 | 新增: w.WriteHeader(201) | |
| 101 | 新增: _, _ = w.Write(data) | |
| 102 | 新增: case r.URL.Path == "/api/mobile/cli/sessions": | |
| 103 | 新增: http.Redirect(w, r, "/api/account", 307) | |
| 104 | 新增: default: | |
| 105 | 新增: t.Errorf("unexpected local upstream operation: %s", r.URL.Path) | |
| 106 | 新增: http.NotFound(w, r) | |
| 107 | 新增: } | |
| 108 | 新增: })) | |
| 109 | 新增: t.Cleanup(control.Close) | |
| 110 | 新增: f.backend, err = mobilelink.OpenWorkbench(context.Background(), control.URL, ticket) | |
| 111 | 新增: if err != nil { | |
| 112 | 新增: t.Fatal(err) | |
| 113 | 新增: } | |
| 114 | 新增: t.Cleanup(f.backend.Close) | |
| 115 | 新增: r, err := relay.New(relay.Config{AdminToken: strings.Repeat("t", 64)}) | |
| 116 | 新增: if err != nil { | |
| 117 | 新增: t.Fatal(err) | |
| 118 | 新增: } | |
| 119 | 新增: rs := httptest.NewServer(r) | |
| 120 | 新增: t.Cleanup(rs.Close) | |
| 121 | 新增: t.Cleanup(func() { _ = r.Close() }) | |
| 122 | 新增: f.base = rs.URL | |
| 123 | 新增: return f | |
| 124 | 新增:} | |
| 125 | 新增: | |
| 126 | 新增:func (f *fixture) startHost(t *testing.T, pin string) relay.Invitation { | |
| 127 | 新增: t.Helper() | |
| 128 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 129 | 新增: room, err := mobilelink.CreateRoom(ctx, f.base, strings.Repeat("t", 64)) | |
| 130 | 新增: if err != nil { | |
| 131 | 新增: t.Fatal(err) | |
| 132 | 新增: } | |
| 133 | 新增: done := make(chan error, 1) | |
| 134 | 新增: go func() { done <- mobilelink.ServeHost(ctx, f.base, room.ID, room.HostToken, f.identity, pin, f.backend) }() | |
| 135 | 新增: t.Cleanup(func() { | |
| 136 | 新增: cancel() | |
| 137 | 新增: select { | |
| 138 | 新增: case <-done: | |
| 139 | 新增: case <-time.After(3 * time.Second): | |
| 140 | 新增: t.Error("host bridge did not stop") | |
| 141 | 新增: } | |
| 142 | 新增: }) | |
| 143 | 新增: return room | |
| 144 | 新增:} | |
| 145 | 新增: | |
| 146 | 新增:func TestNativeRequestsAcrossRealRelay(t *testing.T) { | |
| 147 | 新增: f := newFixture(t) | |
| 148 | 新增: key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) | |
| 149 | 新增: if err != nil { | |
| 150 | 新增: t.Fatal(err) | |
| 151 | 新增: } | |
| 152 | 新增: d := device{key} | |
| 153 | 新增: pin, err := nativeclient.Fingerprint(d) | |
| 154 | 新增: if err != nil { | |
| 155 | 新增: t.Fatal(err) | |
| 156 | 新增: } | |
| 157 | 新增: room := f.startHost(t, pin) | |
| 158 | 新增: c, err := nativeclient.Open(f.base, room.ID, room.ClientToken, f.identity.Pin, d) | |
| 159 | 新增: if err != nil { | |
| 160 | 新增: t.Fatal(err) | |
| 161 | 新增: } | |
| 162 | 新增: t.Cleanup(func() { _ = c.Close() }) | |
| 163 | 新增: p, err := c.Request("GET", "/api/mobile/cli/projects", nil) | |
| 164 | 新增: if err != nil || p.Status != 200 || p.ContentType != "application/json" || !bytes.Contains(p.Body, []byte("B")) { | |
| 165 | 新增: t.Fatalf("project read failed: %v", err) | |
| 166 | 新增: } | |
| 167 | 新增: done := make(chan error, 1) | |
| 168 | 新增: go func() { | |
| 169 | 新增: _, err := c.Request("GET", session+"?after=2", nil) | |
| 170 | 新增: done <- err | |
| 171 | 新增: }() | |
| 172 | 新增: select { | |
| 173 | 新增: case <-f.activeGet: | |
| 174 | 新增: case <-time.After(3 * time.Second): | |
| 175 | 新增: t.Fatal("revision read did not reach host") | |
| 176 | 新增: } | |
| 177 | 新增: message := []byte(`{"text":"在项目 B 运行测试"}`) | |
| 178 | 新增: p, err = c.Request("POST", session+"/messages", message) | |
| 179 | 新增: close(f.finishGet) | |
| 180 | 新增: if err != nil || p.Status != 201 || !bytes.Equal(p.Body, message) { | |
| 181 | 新增: t.Fatalf("concurrent message submission failed: %v", err) | |
| 182 | 新增: } | |
| 183 | 新增: if err := <-done; err != nil { | |
| 184 | 新增: t.Fatal(err) | |
| 185 | 新增: } | |
| 186 | 新增: decision := []byte(`{"request_id":"12345678-1234-4321-aaaa-123456789abc","approval_id":"12345678-1234-4321-aaaa-123456789abd","allow":false}`) | |
| 187 | 新增: p, err = c.Request("POST", session+"/approval", decision) | |
| 188 | 新增: if err != nil || p.Status != 201 || !bytes.Equal(p.Body, decision) { | |
| 189 | 新增: t.Fatalf("approval reply failed: %v", err) | |
| 190 | 新增: } | |
| 191 | 新增: before := f.upstream.Load() | |
| 192 | 新增: for _, path := range []string{"/api/account", "/api/launch", "/api/mobile/cli/sessions/../projects", session + "/%73top", session + "?after=1&after=2", session + "?after=-1", "http://localhost/api/mobile/cli/projects", "//localhost/api/mobile/cli/projects"} { | |
| 193 | 新增: if _, err := c.Request("GET", path, nil); err == nil { | |
| 194 | 新增: t.Errorf("unsafe operation accepted: %s", path) | |
| 195 | 新增: } | |
| 196 | 新增: } | |
| 197 | 新增: if f.upstream.Load() != before { | |
| 198 | 新增: t.Fatal("refused operation reached host") | |
| 199 | 新增: } | |
| 200 | 新增: p, err = c.Request("GET", "/api/mobile/cli/sessions", nil) | |
| 201 | 新增: if err != nil || p.Status != 502 || f.upstream.Load() != before+1 { | |
| 202 | 新增: t.Fatal("host redirect was followed or exposed") | |
| 203 | 新增: } | |
| 204 | 新增: f.locked.Store(true) | |
| 205 | 新增: p, err = c.Request("GET", "/api/mobile/cli/projects", nil) | |
| 206 | 新增: if err != nil || p.Status != 423 { | |
| 207 | 新增: t.Fatalf("account lock lost at bridge: %v", err) | |
| 208 | 新增: } | |
| 209 | 新增: assets := t.TempDir() | |
| 210 | 新增: if err := os.WriteFile(filepath.Join(assets, "mobile.html"), []byte("mobile"), 0600); err != nil { | |
| 211 | 新增: t.Fatal(err) | |
| 212 | 新增: } | |
| 213 | 新增: entry, err := c.StartUI(assets) | |
| 214 | 新增: if err != nil { | |
| 215 | 新增: t.Fatal(err) | |
| 216 | 新增: } | |
| 217 | 新增: u, err := url.Parse(entry) | |
| 218 | 新增: if err != nil || u.Hostname() != "127.0.0.1" || u.Path != "/link-bootstrap" || u.Fragment == "" { | |
| 219 | 新增: t.Fatal("invalid native UI entry") | |
| 220 | 新增: } | |
| 221 | 新增: browser := &http.Client{Transport: &http.Transport{Proxy: nil}, Timeout: 2 * time.Second} | |
| 222 | 新增: defer browser.CloseIdleConnections() | |
| 223 | 新增: res, err := browser.Get(u.Scheme + "://" + u.Host + u.Path) | |
| 224 | 新增: if err != nil { | |
| 225 | 新增: t.Fatal("cannot open native UI bootstrap") | |
| 226 | 新增: } | |
| 227 | 新增: res.Body.Close() | |
| 228 | 新增: if res.StatusCode != 200 { | |
| 229 | 新增: t.Fatal("native UI bootstrap unavailable") | |
| 230 | 新增: } | |
| 231 | 新增: if _, err := c.StartUI(assets); err == nil { | |
| 232 | 新增: t.Fatal("native UI opened twice") | |
| 233 | 新增: } | |
| 234 | 新增: if err := c.Close(); err != nil { | |
| 235 | 新增: t.Fatal(err) | |
| 236 | 新增: } | |
| 237 | 新增: if res, err := browser.Get(u.Scheme + "://" + u.Host + u.Path); err == nil { | |
| 238 | 新增: res.Body.Close() | |
| 239 | 新增: t.Fatal("discarded native UI remained reachable") | |
| 240 | 新增: } | |
| 241 | 新增:} | |
| 242 | 新增: | |
| 243 | 新增:// A valid but independently implemented device can put arbitrary HTTP/2 | |
| 244 | 新增:// messages onto the link; the host enforces the contract independently. | |
| 245 | 新增:func TestPairedPeerCannotBypassHostFilter(t *testing.T) { | |
| 246 | 新增: f := newFixture(t) | |
| 247 | 新增: key, err := remotelink.NewIdentity() | |
| 248 | 新增: if err != nil { | |
| 249 | 新增: t.Fatal(err) | |
| 250 | 新增: } | |
| 251 | 新增: room := f.startHost(t, key.Pin) | |
| 252 | 新增: dial := websocket.Dialer{HandshakeTimeout: 2 * time.Second} | |
| 253 | 新增: ws, _, err := dial.Dial("ws"+strings.TrimPrefix(f.base, "http")+"/v1/rooms/"+room.ID+"/client", http.Header{"Authorization": {"Bearer " + room.ClientToken}}) | |
| 254 | 新增: if err != nil { | |
| 255 | 新增: t.Fatal("test client did not reach relay") | |
| 256 | 新增: } | |
| 257 | 新增: conn, err := remotelink.Client(context.Background(), ws, key, f.identity.Pin) | |
| 258 | 新增: if err != nil { | |
| 259 | 新增: t.Fatal(err) | |
| 260 | 新增: } | |
| 261 | 新增: defer conn.NetConn().Close() | |
| 262 | 新增: cc, err := (&http2.Transport{}).NewClientConn(conn) | |
| 263 | 新增: if err != nil { | |
| 264 | 新增: t.Fatal(err) | |
| 265 | 新增: } | |
| 266 | 新增: defer cc.Close() | |
| 267 | 新增: for _, tc := range []struct { | |
| 268 | 新增: method, path, host, body string | |
| 269 | 新增: want int | |
| 270 | 新增: }{ | |
| 271 | 新增: {"POST", "/api/launch", "cage-mobile.invalid", "{}", 404}, | |
| 272 | 新增: {"GET", "/api/mobile/cli/sessions/../projects", "cage-mobile.invalid", "", 404}, | |
| 273 | 新增: {"GET", session + "?after=1&after=2", "cage-mobile.invalid", "", 404}, | |
| 274 | 新增: {"GET", "/api/mobile/cli/projects", "other-host.invalid", "", 403}, | |
| 275 | 新增: {"POST", session + "/messages", "cage-mobile.invalid", strings.Repeat("x", (72<<10)+1), 413}, | |
| 276 | 新增: {"GET", "/api/mobile/cli/projects", "cage-mobile.invalid", "", 200}, | |
| 277 | 新增: } { | |
| 278 | 新增: req, err := http.NewRequest(tc.method, "https://"+tc.host+tc.path, strings.NewReader(tc.body)) | |
| 279 | 新增: if err != nil { | |
| 280 | 新增: t.Fatal(err) | |
| 281 | 新增: } | |
| 282 | 新增: req.Header.Set("Authorization", "Bearer forged") | |
| 283 | 新增: req.Header.Set("Cookie", "other=forged") | |
| 284 | 新增: req.Header.Set("Origin", "https://foreign.invalid") | |
| 285 | 新增: req.Header.Set("Content-Type", "application/json") | |
| 286 | 新增: res, err := cc.RoundTrip(req) | |
| 287 | 新增: if err != nil { | |
| 288 | 新增: t.Fatalf("unexpected mobile protocol failure: %v", err) | |
| 289 | 新增: } | |
| 290 | 新增: res.Body.Close() | |
| 291 | 新增: if res.StatusCode != tc.want { | |
| 292 | 新增: t.Fatalf("raw %s status=%d, want %d", tc.path, res.StatusCode, tc.want) | |
| 293 | 新增: } | |
| 294 | 新增: } | |
| 295 | 新增: if calls := f.upstream.Load(); calls != 1 { | |
| 296 | 新增: t.Fatalf("host accepted %d upstream requests, want 1", calls) | |
| 297 | 新增: } | |
| 298 | 新增:} | |
| 299 | 新增: | |
| 300 | 新增:func TestLocalBrowserSessionAndHostHeaders(t *testing.T) { | |
| 301 | 新增: f := newFixture(t) | |
| 302 | 新增: id, err := remotelink.NewIdentity() | |
| 303 | 新增: if err != nil { | |
| 304 | 新增: t.Fatal(err) | |
| 305 | 新增: } | |
| 306 | 新增: room := f.startHost(t, id.Pin) | |
| 307 | 新增: client, err := mobilelink.ConnectClient(context.Background(), f.base, room.ID, room.ClientToken, id, f.identity.Pin) | |
| 308 | 新增: if err != nil { | |
| 309 | 新增: t.Fatal(err) | |
| 310 | 新增: } | |
| 311 | 新增: t.Cleanup(func() { _ = client.Close() }) | |
| 312 | 新增: dir := t.TempDir() | |
| 313 | 新增: if err := os.WriteFile(filepath.Join(dir, "mobile.html"), []byte("Cage mobile test"), 0600); err != nil { | |
| 314 | 新增: t.Fatal(err) | |
| 315 | 新增: } | |
| 316 | 新增: web := httptest.NewUnstartedServer(nil) | |
| 317 | 新增: origin := "http://" + web.Listener.Addr().String() | |
| 318 | 新增: b, launch, err := mobilelink.NewBrowser(origin, dir, client) | |
| 319 | 新增: if err != nil { | |
| 320 | 新增: t.Fatal(err) | |
| 321 | 新增: } | |
| 322 | 新增: t.Cleanup(func() { b.Close() }) | |
| 323 | 新增: web.Config.Handler = b | |
| 324 | 新增: web.Start() | |
| 325 | 新增: t.Cleanup(web.Close) | |
| 326 | 新增: entry, _ := url.Parse(launch) | |
| 327 | 新增: body, _ := json.Marshal(map[string]string{"token": entry.Fragment}) | |
| 328 | 新增: call := func(method, path, ref string, cookie *http.Cookie, data []byte) *http.Response { | |
| 329 | 新增: t.Helper() | |
| 330 | 新增: req, _ := http.NewRequest(method, origin+path, bytes.NewReader(data)) | |
| 331 | 新增: if ref != "" { | |
| 332 | 新增: req.Header.Set("Origin", ref) | |
| 333 | 新增: } | |
| 334 | 新增: req.Header.Set("Content-Type", "application/json") | |
| 335 | 新增: req.Header.Set("Authorization", "Bearer untrusted-browser-value") | |
| 336 | 新增: if cookie != nil { | |
| 337 | 新增: req.AddCookie(cookie) | |
| 338 | 新增: req.AddCookie(&http.Cookie{Name: "cage_session_host", Value: "untrusted-browser-value"}) | |
| 339 | 新增: } | |
| 340 | 新增: res, e := web.Client().Do(req) | |
| 341 | 新增: if e != nil { | |
| 342 | 新增: t.Fatal(e) | |
| 343 | 新增: } | |
| 344 | 新增: t.Cleanup(func() { res.Body.Close() }) | |
| 345 | 新增: return res | |
| 346 | 新增: } | |
| 347 | 新增: if res := call("GET", "/", "", nil, nil); res.StatusCode != 401 { | |
| 348 | 新增: t.Fatal("unauthenticated browser obtained UI") | |
| 349 | 新增: } | |
| 350 | 新增: if res := call("GET", "/link-bootstrap?page=archived", "", nil, nil); res.StatusCode != 200 { | |
| 351 | 新增: t.Fatal("native archive entry could not bootstrap") | |
| 352 | 新增: } | |
| 353 | 新增: if res := call("GET", "/link-bootstrap?page=other", "", nil, nil); res.StatusCode != 401 { | |
| 354 | 新增: t.Fatal("unexpected native bootstrap query accepted") | |
| 355 | 新增: } | |
| 356 | 新增: if res := call("POST", "/link-session", "https://untrusted.invalid", nil, body); res.StatusCode != 403 { | |
| 357 | 新增: t.Fatal("cross-origin browser obtained session") | |
| 358 | 新增: } | |
| 359 | 新增: res := call("POST", "/link-session", origin, nil, body) | |
| 360 | 新增: cookies := res.Cookies() | |
| 361 | 新增: if res.StatusCode != 204 || len(cookies) != 1 || !cookies[0].HttpOnly || cookies[0].SameSite != http.SameSiteStrictMode { | |
| 362 | 新增: t.Fatal("browser bootstrap did not issue a protected local cookie") | |
| 363 | 新增: } | |
| 364 | 新增: if res := call("POST", "/link-session", origin, nil, body); res.StatusCode != 401 { | |
| 365 | 新增: t.Fatal("bootstrap was usable twice") | |
| 366 | 新增: } | |
| 367 | 新增: for _, path := range []string{"/", "/?page=archived", "/api/mobile/cli/projects"} { | |
| 368 | 新增: res = call("GET", path, "", cookies[0], nil) | |
| 369 | 新增: if res.StatusCode != 200 || len(res.Cookies()) != 0 { | |
| 370 | 新增: t.Fatalf("local browser route failed or leaked cookie: %s", path) | |
| 371 | 新增: } | |
| 372 | 新增: } | |
| 373 | 新增: if res := call("POST", session+"/messages", "https://untrusted.invalid", cookies[0], []byte("{}")); res.StatusCode != 403 { | |
| 374 | 新增: t.Fatal("foreign origin used authenticated bridge") | |
| 375 | 新增: } | |
| 376 | 新增: if res := call("POST", "/api/account/unlock", origin, cookies[0], []byte("{}")); res.StatusCode != 404 { | |
| 377 | 新增: t.Fatal("non-mobile route exposed to browser") | |
| 378 | 新增: } | |
| 379 | 新增:} | |
| 380 | 新增: | |
| 381 | 新增:func TestSavedNativeClientUsesNewRoomsAndChecksHostIdentity(t *testing.T) { | |
| 382 | 新增: f := newFixture(t) | |
| 383 | 新增: key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) | |
| 384 | 新增: if err != nil { | |
| 385 | 新增: t.Fatal(err) | |
| 386 | 新增: } | |
| 387 | 新增: d := device{key} | |
| 388 | 新增: pin, err := nativeclient.Fingerprint(d) | |
| 389 | 新增: if err != nil { | |
| 390 | 新增: t.Fatal(err) | |
| 391 | 新增: } | |
| 392 | 新增: lookup := "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" | |
| 393 | 新增: wrong := "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBA" | |
| 394 | 新增: if _, err := mobilelink.CreateDiscoverableRoom(context.Background(), f.base, strings.Repeat("x", 64), lookup); err == nil || mobilelink.Retryable(err) { | |
| 395 | 新增: t.Fatal("invalid admin credentials must stop the host service") | |
| 396 | 新增: } | |
| 397 | 新增: if _, err := mobilelink.LookupRoom(context.Background(), f.base, wrong); err == nil { | |
| 398 | 新增: t.Fatal("unregistered lookup token accepted") | |
| 399 | 新增: } | |
| 400 | 新增: other, err := remotelink.NewIdentity() | |
| 401 | 新增: if err != nil { | |
| 402 | 新增: t.Fatal(err) | |
| 403 | 新增: } | |
| 404 | 新增: previous := "" | |
| 405 | 新增: for _, expectedPin := range []string{other.Pin, f.identity.Pin, f.identity.Pin} { | |
| 406 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
| 407 | 新增: inv, err := mobilelink.CreateDiscoverableRoom(ctx, f.base, strings.Repeat("t", 64), lookup) | |
| 408 | 新增: if err != nil { | |
| 409 | 新增: cancel() | |
| 410 | 新增: t.Fatal(err) | |
| 411 | 新增: } | |
| 412 | 新增: if inv.ID == previous { | |
| 413 | 新增: cancel() | |
| 414 | 新增: t.Fatal("room reused after disconnect") | |
| 415 | 新增: } | |
| 416 | 新增: if _, err := mobilelink.CreateDiscoverableRoom(ctx, f.base, strings.Repeat("t", 64), lookup); err == nil || !mobilelink.Retryable(err) { | |
| 417 | 新增: cancel() | |
| 418 | 新增: t.Fatal("an occupied saved room must remain intact and back off") | |
| 419 | 新增: } | |
| 420 | 新增: previous = inv.ID | |
| 421 | 新增: done := make(chan error, 1) | |
| 422 | 新增: go func() { done <- mobilelink.ServeHost(ctx, f.base, inv.ID, inv.HostToken, f.identity, pin, f.backend) }() | |
| 423 | 新增: for { | |
| 424 | 新增: visible, err := mobilelink.LookupRoom(ctx, f.base, lookup) | |
| 425 | 新增: if err == nil && visible.ID == inv.ID { | |
| 426 | 新增: break | |
| 427 | 新增: } | |
| 428 | 新增: if ctx.Err() != nil { | |
| 429 | 新增: cancel() | |
| 430 | 新增: t.Fatal("registered host never became discoverable") | |
| 431 | 新增: } | |
| 432 | 新增: time.Sleep(10 * time.Millisecond) | |
| 433 | 新增: } | |
| 434 | 新增: if _, err := mobilelink.LookupRoom(ctx, f.base, wrong); err == nil { | |
| 435 | 新增: cancel() | |
| 436 | 新增: t.Fatal("incorrect lookup token revealed ready room") | |
| 437 | 新增: } | |
| 438 | 新增: c, err := nativeclient.OpenSaved(f.base, lookup, expectedPin, d) | |
| 439 | 新增: if expectedPin != f.identity.Pin { | |
| 440 | 新增: if err == nil { | |
| 441 | 新增: c.Close() | |
| 442 | 新增: cancel() | |
| 443 | 新增: t.Fatal("saved client accepted the wrong host fingerprint") | |
| 444 | 新增: } | |
| 445 | 新增: } else { | |
| 446 | 新增: if err != nil { | |
| 447 | 新增: cancel() | |
| 448 | 新增: t.Fatal(err) | |
| 449 | 新增: } | |
| 450 | 新增: resp, err := c.Request("GET", "/api/mobile/cli/projects", nil) | |
| 451 | 新增: if err != nil || resp.Status != 200 { | |
| 452 | 新增: c.Close() | |
| 453 | 新增: cancel() | |
| 454 | 新增: t.Fatal("saved native operation failed") | |
| 455 | 新增: } | |
| 456 | 新增: _ = c.Close() | |
| 457 | 新增: } | |
| 458 | 新增: select { | |
| 459 | 新增: case <-done: | |
| 460 | 新增: case <-ctx.Done(): | |
| 461 | 新增: cancel() | |
| 462 | 新增: t.Fatal("used room did not close") | |
| 463 | 新增: } | |
| 464 | 新增: cancel() | |
| 465 | 新增: } | |
| 466 | 新增:} | |
| 467 | 新增: | |
| 468 | 新增:// A phone may have a pending approval open when its network changes. Reading | |
| 469 | 新增:// through the same saved client must recover the transport without replaying it. | |
| 470 | 新增:func TestSavedClientRecoversReadAfterHostDisconnect(t *testing.T) { | |
| 471 | 新增: f := newFixture(t) | |
| 472 | 新增: key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) | |
| 473 | 新增: if err != nil { | |
| 474 | 新增: t.Fatal(err) | |
| 475 | 新增: } | |
| 476 | 新增: d := device{key} | |
| 477 | 新增: pin, err := nativeclient.Fingerprint(d) | |
| 478 | 新增: if err != nil { | |
| 479 | 新增: t.Fatal(err) | |
| 480 | 新增: } | |
| 481 | 新增: lookup := strings.Repeat("A", 43) | |
| 482 | 新增: start := func() func() { | |
| 483 | 新增: t.Helper() | |
| 484 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | |
| 485 | 新增: t.Cleanup(cancel) | |
| 486 | 新增: room, err := mobilelink.CreateDiscoverableRoom(ctx, f.base, strings.Repeat("t", 64), lookup) | |
| 487 | 新增: if err != nil { | |
| 488 | 新增: t.Fatal(err) | |
| 489 | 新增: } | |
| 490 | 新增: done := make(chan struct{}) | |
| 491 | 新增: go func() { | |
| 492 | 新增: defer close(done) | |
| 493 | 新增: _ = mobilelink.ServeHost(ctx, f.base, room.ID, room.HostToken, f.identity, pin, f.backend) | |
| 494 | 新增: }() | |
| 495 | 新增: return func() { cancel(); <-done } | |
| 496 | 新增: } | |
| 497 | 新增: drop := start() | |
| 498 | 新增: c, err := nativeclient.OpenSaved(f.base, lookup, f.identity.Pin, d) | |
| 499 | 新增: if err != nil { | |
| 500 | 新增: t.Fatal(err) | |
| 501 | 新增: } | |
| 502 | 新增: defer c.Close() | |
| 503 | 新增: if _, err := c.Request("GET", "/api/mobile/cli/projects", nil); err != nil { | |
| 504 | 新增: t.Fatal(err) | |
| 505 | 新增: } | |
| 506 | 新增: drop() | |
| 507 | 新增: stop := start() | |
| 508 | 新增: defer stop() | |
| 509 | 新增: | |
| 510 | 新增: calls := f.upstream.Load() | |
| 511 | 新增: if _, err := c.Request("POST", session+"/approval", []byte(`{"allow":true}`)); err == nil { | |
| 512 | 新增: t.Fatal("a pending approval silently crossed into the replacement connection") | |
| 513 | 新增: } | |
| 514 | 新增: if f.upstream.Load() != calls { | |
| 515 | 新增: t.Fatal("approval reached the host") | |
| 516 | 新增: } | |
| 517 | 新增: results := make(chan error, 2) | |
| 518 | 新增: for range 2 { | |
| 519 | 新增: go func() { | |
| 520 | 新增: reply, err := c.Request("GET", "/api/mobile/cli/projects", nil) | |
| 521 | 新增: if err == nil && reply.Status != http.StatusOK { | |
| 522 | 新增: err = fmt.Errorf("unexpected status %d", reply.Status) | |
| 523 | 新增: } | |
| 524 | 新增: results <- err | |
| 525 | 新增: }() | |
| 526 | 新增: } | |
| 527 | 新增: for range 2 { | |
| 528 | 新增: if err := <-results; err != nil { | |
| 529 | 新增: t.Fatal(err) | |
| 530 | 新增: } | |
| 531 | 新增: } | |
| 532 | 新增: if got := f.upstream.Load() - calls; got != 2 { | |
| 533 | 新增: t.Fatalf("expected only two recovered reads, got %d requests", got) | |
| 534 | 新增: } | |
| 535 | 新增:} | |
| @@ -0,0 +1,269 @@ | ||
| 1 | 新增:// Package nativeclient has a gomobile-bindable API for a native application. | |
| 2 | 新增:// Platform code supplies the device signer and its previously verified host | |
| 3 | 新增:// pin. Relay room tokens and the native signer stay outside the WebView. | |
| 4 | 新增:package nativeclient | |
| 5 | 新增: | |
| 6 | 新增:import ( | |
| 7 | 新增: "context" | |
| 8 | 新增: "crypto" | |
| 9 | 新增: "crypto/ecdsa" | |
| 10 | 新增: "crypto/elliptic" | |
| 11 | 新增: "crypto/sha256" | |
| 12 | 新增: "crypto/x509" | |
| 13 | 新增: "encoding/base64" | |
| 14 | 新增: "errors" | |
| 15 | 新增: "io" | |
| 16 | 新增: "log" | |
| 17 | 新增: "net" | |
| 18 | 新增: "net/http" | |
| 19 | 新增: "path/filepath" | |
| 20 | 新增: "sync" | |
| 21 | 新增: "time" | |
| 22 | 新增: | |
| 23 | 新增: "github.com/sylvinus/agent-vm/internal/mobilelink" | |
| 24 | 新增: "github.com/sylvinus/agent-vm/internal/remotelink" | |
| 25 | 新增: "golang.org/x/sync/singleflight" | |
| 26 | 新增:) | |
| 27 | 新增: | |
| 28 | 新增:// DeviceSigner signs SHA-256 digests with the same non-exportable P-256 key | |
| 29 | 新增:// that produced PublicKeyDER. Signatures use ASN.1 DER (X9.62), not raw r||s. | |
| 30 | 新增:type DeviceSigner interface { | |
| 31 | 新增: PublicKeyDER() ([]byte, error) | |
| 32 | 新增: SignSHA256(digest []byte) ([]byte, error) | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:type signerAdapter struct { | |
| 36 | 新增: device DeviceSigner | |
| 37 | 新增: public *ecdsa.PublicKey | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:func signer(device DeviceSigner) (*signerAdapter, error) { | |
| 41 | 新增: if device == nil { | |
| 42 | 新增: return nil, errors.New("missing device signer") | |
| 43 | 新增: } | |
| 44 | 新增: der, err := device.PublicKeyDER() | |
| 45 | 新增: if err != nil { | |
| 46 | 新增: return nil, errors.New("cannot read device public key") | |
| 47 | 新增: } | |
| 48 | 新增: key, err := x509.ParsePKIXPublicKey(der) | |
| 49 | 新增: pub, ok := key.(*ecdsa.PublicKey) | |
| 50 | 新增: if err != nil || !ok || pub.Curve != elliptic.P256() { | |
| 51 | 新增: return nil, errors.New("device public key must be a P-256 SubjectPublicKeyInfo") | |
| 52 | 新增: } | |
| 53 | 新增: return &signerAdapter{device, pub}, nil | |
| 54 | 新增:} | |
| 55 | 新增: | |
| 56 | 新增:func (s *signerAdapter) Public() crypto.PublicKey { return s.public } | |
| 57 | 新增:func (s *signerAdapter) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) { | |
| 58 | 新增: if opts.HashFunc() != crypto.SHA256 || len(digest) != sha256.Size { | |
| 59 | 新增: return nil, errors.New("unsupported device signature algorithm") | |
| 60 | 新增: } | |
| 61 | 新增: return s.device.SignSHA256(digest) | |
| 62 | 新增:} | |
| 63 | 新增: | |
| 64 | 新增:// Fingerprint identifies the platform key that the host must explicitly trust | |
| 65 | 新增:// through a channel independent of the relay. | |
| 66 | 新增:func Fingerprint(device DeviceSigner) (string, error) { | |
| 67 | 新增: adapter, err := signer(device) | |
| 68 | 新增: if err != nil { | |
| 69 | 新增: return "", err | |
| 70 | 新增: } | |
| 71 | 新增: der, err := x509.MarshalPKIXPublicKey(adapter.public) | |
| 72 | 新增: if err != nil { | |
| 73 | 新增: return "", err | |
| 74 | 新增: } | |
| 75 | 新增: digest := sha256.Sum256(der) | |
| 76 | 新增: return "sha256:" + base64.StdEncoding.EncodeToString(digest[:]), nil | |
| 77 | 新增:} | |
| 78 | 新增: | |
| 79 | 新增:type Client struct { | |
| 80 | 新增: link *mobilelink.Client | |
| 81 | 新增: recoverLink func(context.Context) (*mobilelink.Client, error) | |
| 82 | 新增: recovery singleflight.Group | |
| 83 | 新增: lifetime context.Context | |
| 84 | 新增: cancel context.CancelFunc | |
| 85 | 新增: mu sync.Mutex | |
| 86 | 新增: closed bool | |
| 87 | 新增: server *http.Server | |
| 88 | 新增: listener net.Listener | |
| 89 | 新增: browser *mobilelink.Browser | |
| 90 | 新增:} | |
| 91 | 新增: | |
| 92 | 新增:// Open connects to a pre-provisioned room. The native app owns relay trust, | |
| 93 | 新增:// peer pin persistence, first-time pairing, and its foreground lifecycle. | |
| 94 | 新增:func Open(relayOrigin, roomID, clientToken, trustedHostPin string, device DeviceSigner) (*Client, error) { | |
| 95 | 新增: adapter, err := signer(device) | |
| 96 | 新增: if err != nil { | |
| 97 | 新增: return nil, err | |
| 98 | 新增: } | |
| 99 | 新增: identity, err := remotelink.IdentityFromSigner(adapter) | |
| 100 | 新增: if err != nil { | |
| 101 | 新增: return nil, err | |
| 102 | 新增: } | |
| 103 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) | |
| 104 | 新增: defer cancel() | |
| 105 | 新增: link, err := mobilelink.ConnectClient(ctx, relayOrigin, roomID, clientToken, identity, trustedHostPin) | |
| 106 | 新增: if err != nil { | |
| 107 | 新增: return nil, err | |
| 108 | 新增: } | |
| 109 | 新增: return &Client{link: link}, nil | |
| 110 | 新增:} | |
| 111 | 新增: | |
| 112 | 新增:// OpenSaved resolves a fresh room for an already verified host. It does not | |
| 113 | 新增:// send any application operation, including during recovery after disconnect. | |
| 114 | 新增:func OpenSaved(relayOrigin, lookupToken, trustedHostPin string, device DeviceSigner) (*Client, error) { | |
| 115 | 新增: adapter, err := signer(device) | |
| 116 | 新增: if err != nil { | |
| 117 | 新增: return nil, err | |
| 118 | 新增: } | |
| 119 | 新增: identity, err := remotelink.IdentityFromSigner(adapter) | |
| 120 | 新增: if err != nil { | |
| 121 | 新增: return nil, err | |
| 122 | 新增: } | |
| 123 | 新增: lifetime, cancel := context.WithCancel(context.Background()) | |
| 124 | 新增: dial := func(parent context.Context) (*mobilelink.Client, error) { | |
| 125 | 新增: ctx, stop := context.WithTimeout(parent, 25*time.Second) | |
| 126 | 新增: defer stop() | |
| 127 | 新增: room, err := lookupSaved(ctx, relayOrigin, lookupToken) | |
| 128 | 新增: if err != nil { | |
| 129 | 新增: return nil, err | |
| 130 | 新增: } | |
| 131 | 新增: return mobilelink.ConnectClient(ctx, relayOrigin, room.ID, room.ClientToken, identity, trustedHostPin) | |
| 132 | 新增: } | |
| 133 | 新增: link, err := dial(lifetime) | |
| 134 | 新增: if err != nil { | |
| 135 | 新增: cancel() | |
| 136 | 新增: return nil, err | |
| 137 | 新增: } | |
| 138 | 新增: return &Client{link: link, recoverLink: dial, lifetime: lifetime, cancel: cancel}, nil | |
| 139 | 新增:} | |
| 140 | 新增: | |
| 141 | 新增:func lookupSaved(ctx context.Context, relayOrigin, lookupToken string) (mobilelink.ClientInvitation, error) { | |
| 142 | 新增: ctx, cancel := context.WithTimeout(ctx, 10*time.Second) | |
| 143 | 新增: defer cancel() | |
| 144 | 新增: room, err := mobilelink.LookupRoom(ctx, relayOrigin, lookupToken) | |
| 145 | 新增: // A freshly disconnected host needs a moment to publish its next room. | |
| 146 | 新增: // Only repeat a read of the relay directory. Authentication and every | |
| 147 | 新增: // application request remain single attempts. | |
| 148 | 新增: for _, delay := range []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, time.Second} { | |
| 149 | 新增: if !errors.Is(err, mobilelink.ErrNoInvitation) { | |
| 150 | 新增: break | |
| 151 | 新增: } | |
| 152 | 新增: timer := time.NewTimer(delay) | |
| 153 | 新增: select { | |
| 154 | 新增: case <-ctx.Done(): | |
| 155 | 新增: timer.Stop() | |
| 156 | 新增: return room, ctx.Err() | |
| 157 | 新增: case <-timer.C: | |
| 158 | 新增: } | |
| 159 | 新增: room, err = mobilelink.LookupRoom(ctx, relayOrigin, lookupToken) | |
| 160 | 新增: } | |
| 161 | 新增: return room, err | |
| 162 | 新增:} | |
| 163 | 新增: | |
| 164 | 新增:type Response struct { | |
| 165 | 新增: Status int | |
| 166 | 新增: ContentType string | |
| 167 | 新增: Body []byte | |
| 168 | 新增:} | |
| 169 | 新增: | |
| 170 | 新增:// Request accepts only the mobile operation allowlist. Call off the main UI thread. | |
| 171 | 新增:func (c *Client) Request(method, path string, body []byte) (*Response, error) { | |
| 172 | 新增: reply, err := c.Do(context.Background(), method, path, body) | |
| 173 | 新增: if err != nil { | |
| 174 | 新增: return nil, err | |
| 175 | 新增: } | |
| 176 | 新增: return &Response{reply.Status, reply.ContentType, reply.Body}, nil | |
| 177 | 新增:} | |
| 178 | 新增: | |
| 179 | 新增:// Do keeps the local WebView and pending draft alive across transport loss. | |
| 180 | 新增:// Only a read may reopen the saved pairing. Never resend a mutation here. | |
| 181 | 新增:func (c *Client) Do(ctx context.Context, method, path string, body []byte) (*mobilelink.Reply, error) { | |
| 182 | 新增: c.mu.Lock() | |
| 183 | 新增: link, closed := c.link, c.closed | |
| 184 | 新增: c.mu.Unlock() | |
| 185 | 新增: if closed { | |
| 186 | 新增: return nil, net.ErrClosed | |
| 187 | 新增: } | |
| 188 | 新增: reply, err := link.Do(ctx, method, path, body) | |
| 189 | 新增: if err == nil || method != http.MethodGet || c.recoverLink == nil || ctx.Err() != nil || !link.Disconnected() { | |
| 190 | 新增: return reply, err | |
| 191 | 新增: } | |
| 192 | 新增: result := c.recovery.DoChan("link", func() (any, error) { | |
| 193 | 新增: c.mu.Lock() | |
| 194 | 新增: current, closed := c.link, c.closed | |
| 195 | 新增: c.mu.Unlock() | |
| 196 | 新增: if closed { | |
| 197 | 新增: return nil, net.ErrClosed | |
| 198 | 新增: } | |
| 199 | 新增: if current != link { | |
| 200 | 新增: return current, nil | |
| 201 | 新增: } | |
| 202 | 新增: next, err := c.recoverLink(c.lifetime) | |
| 203 | 新增: if err != nil { | |
| 204 | 新增: return nil, err | |
| 205 | 新增: } | |
| 206 | 新增: c.mu.Lock() | |
| 207 | 新增: defer c.mu.Unlock() | |
| 208 | 新增: if c.closed { | |
| 209 | 新增: next.Close() | |
| 210 | 新增: return nil, net.ErrClosed | |
| 211 | 新增: } | |
| 212 | 新增: c.link = next | |
| 213 | 新增: link.Close() | |
| 214 | 新增: return next, nil | |
| 215 | 新增: }) | |
| 216 | 新增: select { | |
| 217 | 新增: case <-ctx.Done(): | |
| 218 | 新增: return nil, ctx.Err() | |
| 219 | 新增: case r := <-result: | |
| 220 | 新增: if r.Err != nil { | |
| 221 | 新增: return nil, r.Err | |
| 222 | 新增: } | |
| 223 | 新增: return r.Val.(*mobilelink.Client).Do(ctx, method, path, body) | |
| 224 | 新增: } | |
| 225 | 新增:} | |
| 226 | 新增: | |
| 227 | 新增:// StartUI serves the app's shipped mobile.html and assets on an ephemeral | |
| 228 | 新增:// IPv4 loopback port. Pass the one-use URL directly to a private WebView. | |
| 229 | 新增:// The native shell must allow navigation only to this exact loopback origin | |
| 230 | 新增:// and avoid logging the URL. Call Close when discarding this connection. | |
| 231 | 新增:func (c *Client) StartUI(assetsDirectory string) (string, error) { | |
| 232 | 新增: c.mu.Lock() | |
| 233 | 新增: defer c.mu.Unlock() | |
| 234 | 新增: if c.closed || c.server != nil || !filepath.IsAbs(assetsDirectory) { | |
| 235 | 新增: return "", errors.New("UI needs an open connection, an absolute asset directory, and a single start") | |
| 236 | 新增: } | |
| 237 | 新增: listener, err := net.Listen("tcp4", "127.0.0.1:0") | |
| 238 | 新增: if err != nil { | |
| 239 | 新增: return "", errors.New("cannot open local mobile UI listener") | |
| 240 | 新增: } | |
| 241 | 新增: browser, launchURL, err := mobilelink.NewBrowser("http://"+listener.Addr().String(), assetsDirectory, c) | |
| 242 | 新增: if err != nil { | |
| 243 | 新增: listener.Close() | |
| 244 | 新增: return "", err | |
| 245 | 新增: } | |
| 246 | 新增: server := &http.Server{Handler: browser, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, | |
| 247 | 新增: WriteTimeout: 45 * time.Second, IdleTimeout: time.Minute, MaxHeaderBytes: 16 << 10, ErrorLog: log.New(io.Discard, "", 0)} | |
| 248 | 新增: c.server, c.listener, c.browser = server, listener, browser | |
| 249 | 新增: go func() { _ = server.Serve(listener) }() | |
| 250 | 新增: return launchURL, nil | |
| 251 | 新增:} | |
| 252 | 新增: | |
| 253 | 新增:func (c *Client) Close() error { | |
| 254 | 新增: c.mu.Lock() | |
| 255 | 新增: defer c.mu.Unlock() | |
| 256 | 新增: if c.closed { | |
| 257 | 新增: return nil | |
| 258 | 新增: } | |
| 259 | 新增: c.closed = true | |
| 260 | 新增: if c.cancel != nil { | |
| 261 | 新增: c.cancel() | |
| 262 | 新增: } | |
| 263 | 新增: if c.server != nil { | |
| 264 | 新增: _ = c.server.Close() | |
| 265 | 新增: _ = c.listener.Close() | |
| 266 | 新增: _ = c.browser.Close() | |
| 267 | 新增: } | |
| 268 | 新增: return c.link.Close() | |
| 269 | 新增:} | |
| @@ -0,0 +1,206 @@ | ||
| 1 | 新增:// Package mobilelink connects a paired mobile client to the mobile | |
| 2 | 新增:// operations of a single Cage host. It never exposes the full workbench API. | |
| 3 | 新增:package mobilelink | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bytes" | |
| 7 | 新增: "context" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "io" | |
| 10 | 新增: "mime" | |
| 11 | 新增: "net/http" | |
| 12 | 新增: "net/url" | |
| 13 | 新增: "regexp" | |
| 14 | 新增: "strconv" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "time" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:const ( | |
| 20 | 新增: maxRequest = 72 << 10 | |
| 21 | 新增: maxResponse = 4 << 20 | |
| 22 | 新增: linkOrigin = "https://cage-mobile.invalid" | |
| 23 | 新增:) | |
| 24 | 新增: | |
| 25 | 新增:var sessionPath = regexp.MustCompile(`^/api/mobile/cli/sessions/[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}(/messages|/media|/stop|/approval|/open|/metadata|/account|/delete|/archive|/restore|/purge)?$`) | |
| 26 | 新增: | |
| 27 | 新增:var surfacePath = regexp.MustCompile(`^/api/mobile/(?:browser|desktop)/[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/(frame|action|close)$`) | |
| 28 | 新增: | |
| 29 | 新增:var epochID = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) | |
| 30 | 新增: | |
| 31 | 新增:var frameQuery = regexp.MustCompile(`^after=([0-9a-f]{32})$`) | |
| 32 | 新增: | |
| 33 | 新增:// FrameAfter accepts a single opaque frame tag in its canonical wire form. | |
| 34 | 新增:func FrameAfter(query string) (string, bool) { | |
| 35 | 新增: match := frameQuery.FindStringSubmatch(query) | |
| 36 | 新增: if match == nil { | |
| 37 | 新增: return "", false | |
| 38 | 新增: } | |
| 39 | 新增: return match[1], true | |
| 40 | 新增:} | |
| 41 | 新增: | |
| 42 | 新增:func allowed(method string, u *url.URL) bool { | |
| 43 | 新增: if u == nil || u.RawPath != "" || u.Opaque != "" || u.User != nil || u.Fragment != "" || u.ForceQuery { | |
| 44 | 新增: return false | |
| 45 | 新增: } | |
| 46 | 新增: if u.Path == "/api/mobile/cli/sessions" && u.RawQuery == "archived=true" { | |
| 47 | 新增: return method == http.MethodGet | |
| 48 | 新增: } | |
| 49 | 新增: if u.RawQuery == "" { | |
| 50 | 新增: switch u.Path { | |
| 51 | 新增: case "/api/mobile/browser/open", "/api/mobile/desktop/open", "/api/mobile/device": | |
| 52 | 新增: return method == http.MethodPost | |
| 53 | 新增: case "/api/mobile/cli/projects": | |
| 54 | 新增: return method == http.MethodGet | |
| 55 | 新增: case "/api/mobile/cli/sessions", "/api/mobile/browser/favorites": | |
| 56 | 新增: return method == http.MethodGet || method == http.MethodPost | |
| 57 | 新增: } | |
| 58 | 新增: } | |
| 59 | 新增: if match := surfacePath.FindStringSubmatch(u.Path); match != nil { | |
| 60 | 新增: if u.RawQuery == "" { | |
| 61 | 新增: return (match[1] == "frame" && method == http.MethodGet) || (match[1] != "frame" && method == http.MethodPost) | |
| 62 | 新增: } | |
| 63 | 新增: _, ok := FrameAfter(u.RawQuery) | |
| 64 | 新增: return ok && match[1] == "frame" && method == http.MethodGet && strings.HasPrefix(u.Path, "/api/mobile/browser/") | |
| 65 | 新增: } | |
| 66 | 新增: match := sessionPath.FindStringSubmatch(u.Path) | |
| 67 | 新增: if match == nil { | |
| 68 | 新增: return false | |
| 69 | 新增: } | |
| 70 | 新增: if match[1] != "" { | |
| 71 | 新增: return method == http.MethodPost && u.RawQuery == "" | |
| 72 | 新增: } | |
| 73 | 新增: if method != http.MethodGet { | |
| 74 | 新增: return false | |
| 75 | 新增: } | |
| 76 | 新增: if u.RawQuery == "" { | |
| 77 | 新增: return true | |
| 78 | 新增: } | |
| 79 | 新增: fields := strings.Split(u.RawQuery, "&") | |
| 80 | 新增: if len(fields) > 2 { | |
| 81 | 新增: return false | |
| 82 | 新增: } | |
| 83 | 新增: var after string | |
| 84 | 新增: var hasEpoch bool | |
| 85 | 新增: for _, field := range fields { | |
| 86 | 新增: key, value, _ := strings.Cut(field, "=") | |
| 87 | 新增: switch key { | |
| 88 | 新增: case "after": | |
| 89 | 新增: if after != "" || value == "" { | |
| 90 | 新增: return false | |
| 91 | 新增: } | |
| 92 | 新增: after = value | |
| 93 | 新增: case "epoch": | |
| 94 | 新增: if hasEpoch || !epochID.MatchString(value) { | |
| 95 | 新增: return false | |
| 96 | 新增: } | |
| 97 | 新增: hasEpoch = true | |
| 98 | 新增: default: | |
| 99 | 新增: return false | |
| 100 | 新增: } | |
| 101 | 新增: } | |
| 102 | 新增: if after == "" { | |
| 103 | 新增: return false | |
| 104 | 新增: } | |
| 105 | 新增: for _, digit := range after { | |
| 106 | 新增: if digit < '0' || digit > '9' { | |
| 107 | 新增: return false | |
| 108 | 新增: } | |
| 109 | 新增: } | |
| 110 | 新增: _, err := strconv.ParseUint(after, 10, 64) | |
| 111 | 新增: return err == nil | |
| 112 | 新增:} | |
| 113 | 新增: | |
| 114 | 新增:// Reply carries only application data. Browser cookies, redirects, hop headers | |
| 115 | 新增:// and upstream authentication fields never cross the device link. | |
| 116 | 新增:type Reply struct { | |
| 117 | 新增: Status int | |
| 118 | 新增: ContentType string | |
| 119 | 新增: Body []byte | |
| 120 | 新增:} | |
| 121 | 新增: | |
| 122 | 新增:type performFunc func(context.Context, string, string, []byte) (*Reply, error) | |
| 123 | 新增: | |
| 124 | 新增:func limited(r io.Reader, limit int64) ([]byte, error) { | |
| 125 | 新增: data, err := io.ReadAll(io.LimitReader(r, limit+1)) | |
| 126 | 新增: if err != nil || int64(len(data)) > limit { | |
| 127 | 新增: return nil, errors.New("payload exceeds limit or could not be read") | |
| 128 | 新增: } | |
| 129 | 新增: return data, nil | |
| 130 | 新增:} | |
| 131 | 新增: | |
| 132 | 新增:// operations checks the method and route before reading data. Callers establish | |
| 133 | 新增:// the peer identity or the local browser session before invoking this handler. | |
| 134 | 新增:func operations(do performFunc) http.Handler { | |
| 135 | 新增: return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 136 | 新增: w.Header().Set("Cache-Control", "no-store") | |
| 137 | 新增: w.Header().Set("X-Content-Type-Options", "nosniff") | |
| 138 | 新增: if !allowed(r.Method, r.URL) { | |
| 139 | 新增: http.NotFound(w, r) | |
| 140 | 新增: return | |
| 141 | 新增: } | |
| 142 | 新增: if r.Method == http.MethodPost { | |
| 143 | 新增: kind, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) | |
| 144 | 新增: if kind != "application/json" { | |
| 145 | 新增: http.Error(w, "JSON is required", http.StatusUnsupportedMediaType) | |
| 146 | 新增: return | |
| 147 | 新增: } | |
| 148 | 新增: } | |
| 149 | 新增: body, err := limited(r.Body, maxRequest) | |
| 150 | 新增: if err != nil { | |
| 151 | 新增: http.Error(w, "request body too large or unreadable", http.StatusRequestEntityTooLarge) | |
| 152 | 新增: return | |
| 153 | 新增: } | |
| 154 | 新增: if r.Method == http.MethodGet && len(body) != 0 { | |
| 155 | 新增: http.Error(w, "GET must not have a body", http.StatusBadRequest) | |
| 156 | 新增: return | |
| 157 | 新增: } | |
| 158 | 新增: reply, err := do(r.Context(), r.Method, r.URL.RequestURI(), body) | |
| 159 | 新增: if err != nil { | |
| 160 | 新增: http.Error(w, "与电脑的连接已中断。请检查手机网络和电脑上的 Cage,再重新读取会话。", http.StatusBadGateway) | |
| 161 | 新增: return | |
| 162 | 新增: } | |
| 163 | 新增: w.Header().Set("Content-Type", reply.ContentType) | |
| 164 | 新增: w.WriteHeader(reply.Status) | |
| 165 | 新增: if reply.Status != http.StatusNoContent { | |
| 166 | 新增: _, _ = w.Write(reply.Body) | |
| 167 | 新增: } | |
| 168 | 新增: }) | |
| 169 | 新增:} | |
| 170 | 新增: | |
| 171 | 新增:func request(ctx context.Context, client http.RoundTripper, origin, method, path string, body []byte, localOrigin bool) (*Reply, error) { | |
| 172 | 新增: u, err := url.ParseRequestURI(path) | |
| 173 | 新增: if err != nil || u.IsAbs() || u.Host != "" || !allowed(method, u) || len(body) > maxRequest || (method == http.MethodGet && len(body) > 0) { | |
| 174 | 新增: return nil, errors.New("mobile operation refused") | |
| 175 | 新增: } | |
| 176 | 新增: ctx, cancel := context.WithTimeout(ctx, 40*time.Second) | |
| 177 | 新增: defer cancel() | |
| 178 | 新增: req, err := http.NewRequestWithContext(ctx, method, origin+path, bytes.NewReader(body)) | |
| 179 | 新增: if err != nil { | |
| 180 | 新增: return nil, errors.New("invalid mobile operation") | |
| 181 | 新增: } | |
| 182 | 新增: req.GetBody = nil // A mutation with a lost response is never replayed here. | |
| 183 | 新增: if method == http.MethodPost { | |
| 184 | 新增: req.Header.Set("Content-Type", "application/json") | |
| 185 | 新增: } | |
| 186 | 新增: if localOrigin { | |
| 187 | 新增: req.Header.Set("Origin", origin) | |
| 188 | 新增: } | |
| 189 | 新增: res, err := client.RoundTrip(req) | |
| 190 | 新增: if err != nil { | |
| 191 | 新增: return nil, errors.New("mobile operation interrupted") | |
| 192 | 新增: } | |
| 193 | 新增: defer res.Body.Close() | |
| 194 | 新增: if res.StatusCode < 200 || (res.StatusCode >= 300 && res.StatusCode < 400) { | |
| 195 | 新增: return nil, errors.New("unexpected mobile response status") | |
| 196 | 新增: } | |
| 197 | 新增: data, err := limited(res.Body, maxResponse) | |
| 198 | 新增: if err != nil { | |
| 199 | 新增: return nil, err | |
| 200 | 新增: } | |
| 201 | 新增: contentType := "text/plain; charset=utf-8" | |
| 202 | 新增: if kind, _, _ := mime.ParseMediaType(res.Header.Get("Content-Type")); kind == "application/json" { | |
| 203 | 新增: contentType = "application/json" | |
| 204 | 新增: } | |
| 205 | 新增: return &Reply{res.StatusCode, contentType, data}, nil | |
| 206 | 新增:} | |
| @@ -0,0 +1,75 @@ | ||
| 1 | 新增:package mobilelink | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "net/url" | |
| 5 | 新增: "strings" | |
| 6 | 新增: "testing" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func TestSnapshotPollingQuery(t *testing.T) { | |
| 10 | 新增: const id = "12345678-1234-4321-aaaa-123456789abc" | |
| 11 | 新增: for _, tc := range []struct { | |
| 12 | 新增: query string | |
| 13 | 新增: want bool | |
| 14 | 新增: }{ | |
| 15 | 新增: {"", true}, {"after=0", true}, {"after=18446744073709551615", true}, | |
| 16 | 新增: {"after=2&epoch=" + id, true}, {"epoch=" + id + "&after=2", true}, | |
| 17 | 新增: {"epoch=" + id, false}, {"after=2&epoch=", false}, {"after=2&epoch=" + strings.ToUpper(id), false}, | |
| 18 | 新增: {"after=2&epoch=12345678-1234-5321-aaaa-123456789abc", false}, | |
| 19 | 新增: {"after=2&epoch=12345678-1234-4321-0aaa-123456789abc", false}, | |
| 20 | 新增: {"after=-1&epoch=" + id, false}, {"after=0&after=1", false}, {"after=1&other=x", false}, | |
| 21 | 新增: {"after=1&epoch=" + id + "&epoch=" + id, false}, {"after=%31&epoch=" + id, false}, | |
| 22 | 新增: {"after=18446744073709551616", false}, | |
| 23 | 新增: } { | |
| 24 | 新增: u := &url.URL{Path: "/api/mobile/cli/sessions/" + id, RawQuery: tc.query} | |
| 25 | 新增: if got := allowed("GET", u); got != tc.want { | |
| 26 | 新增: t.Errorf("poll query %q allowed=%v, want %v", tc.query, got, tc.want) | |
| 27 | 新增: } | |
| 28 | 新增: } | |
| 29 | 新增:} | |
| 30 | 新增: | |
| 31 | 新增:func TestBrowserFrameQuery(t *testing.T) { | |
| 32 | 新增: const tag = "b542cd94286a2489bc2df1241b043c76" | |
| 33 | 新增: const id = "12345678-1234-4321-aaaa-123456789abc" | |
| 34 | 新增: for _, tc := range []struct { | |
| 35 | 新增: method, surface, operation, query string | |
| 36 | 新增: want bool | |
| 37 | 新增: }{ | |
| 38 | 新增: {"GET", "browser", "frame", "after=" + tag, true}, | |
| 39 | 新增: {"GET", "browser", "frame", "after=" + tag + "&after=" + tag, false}, | |
| 40 | 新增: {"GET", "browser", "frame", "after=" + strings.ToUpper(tag), false}, | |
| 41 | 新增: {"POST", "browser", "action", "after=" + tag, false}, | |
| 42 | 新增: {"GET", "desktop", "frame", "after=" + tag, false}, | |
| 43 | 新增: } { | |
| 44 | 新增: u := &url.URL{Path: "/api/mobile/" + tc.surface + "/" + id + "/" + tc.operation, RawQuery: tc.query} | |
| 45 | 新增: if allowed(tc.method, u) != tc.want { | |
| 46 | 新增: t.Errorf("unexpected result for %s %s", tc.method, u.RequestURI()) | |
| 47 | 新增: } | |
| 48 | 新增: } | |
| 49 | 新增:} | |
| 50 | 新增: | |
| 51 | 新增:func TestSessionListMutations(t *testing.T) { | |
| 52 | 新增: for _, operation := range []string{"metadata", "delete", "archive", "restore", "purge"} { | |
| 53 | 新增: u := &url.URL{Path: "/api/mobile/cli/sessions/12345678-1234-4321-aaaa-123456789abc/" + operation} | |
| 54 | 新增: if !allowed("POST", u) || allowed("GET", u) || allowed("DELETE", u) { | |
| 55 | 新增: t.Fatal("mutation method boundary", operation) | |
| 56 | 新增: } | |
| 57 | 新增: u.RawQuery = "after=1" | |
| 58 | 新增: if allowed("POST", u) { | |
| 59 | 新增: t.Fatal("mutation query accepted", operation) | |
| 60 | 新增: } | |
| 61 | 新增: } | |
| 62 | 新增:} | |
| 63 | 新增: | |
| 64 | 新增:func TestArchivedSessionQuery(t *testing.T) { | |
| 65 | 新增: u := &url.URL{Path: "/api/mobile/cli/sessions", RawQuery: "archived=true"} | |
| 66 | 新增: if !allowed("GET", u) || allowed("POST", u) { | |
| 67 | 新增: t.Fatal("archive query method") | |
| 68 | 新增: } | |
| 69 | 新增: for _, query := range []string{"archived=false", "archived=true&other=1", "archived=true&archived=true"} { | |
| 70 | 新增: u.RawQuery = query | |
| 71 | 新增: if allowed("GET", u) { | |
| 72 | 新增: t.Fatal("unexpected archive query", query) | |
| 73 | 新增: } | |
| 74 | 新增: } | |
| 75 | 新增:} | |
| @@ -0,0 +1,137 @@ | ||
| 1 | 新增:package mobilelink | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "crypto/ed25519" | |
| 6 | 新增: "crypto/rand" | |
| 7 | 新增: "crypto/tls" | |
| 8 | 新增: "encoding/base64" | |
| 9 | 新增: "encoding/json" | |
| 10 | 新增: "errors" | |
| 11 | 新增: "io" | |
| 12 | 新增: "strings" | |
| 13 | 新增: "time" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/sylvinus/agent-vm/internal/relay" | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/remotelink" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:// The optical channel transfers a temporary TLS client seed and the pinned | |
| 20 | 新增:// server identity. Neither seed nor persistent lookup token goes to the relay. | |
| 21 | 新增:type PairCode struct { | |
| 22 | 新增: Relay string `json:"r,omitempty"` | |
| 23 | 新增: Room string `json:"i"` | |
| 24 | 新增: Token string `json:"t"` | |
| 25 | 新增: Seed []byte `json:"s"` | |
| 26 | 新增: Host string `json:"h"` | |
| 27 | 新增: Expires int64 `json:"e"` | |
| 28 | 新增:} | |
| 29 | 新增:type PairedHost struct { | |
| 30 | 新增: Version int `json:"version"` | |
| 31 | 新增: Relay string `json:"relay"` | |
| 32 | 新增: HostPin string `json:"host_pin"` | |
| 33 | 新增: Lookup string `json:"lookup_token"` | |
| 34 | 新增:} | |
| 35 | 新增: | |
| 36 | 新增:func NewPairCode(origin string, room relay.Invitation, host string) (PairCode, string, error) { | |
| 37 | 新增: seed := make([]byte, ed25519.SeedSize) | |
| 38 | 新增: if _, err := rand.Read(seed); err != nil { | |
| 39 | 新增: return PairCode{}, "", err | |
| 40 | 新增: } | |
| 41 | 新增: code := PairCode{Relay: origin, Room: room.ID, Token: room.ClientToken, Seed: seed, Host: host, Expires: room.ExpiresAt.Unix()} | |
| 42 | 新增: if origin == OfficialRelay { | |
| 43 | 新增: code.Relay = "" | |
| 44 | 新增: } | |
| 45 | 新增: b, err := json.Marshal(code) | |
| 46 | 新增: return code, "CAGE1:" + string(b), err | |
| 47 | 新增:} | |
| 48 | 新增:func (p PairCode) origin() string { | |
| 49 | 新增: if p.Relay == "" { | |
| 50 | 新增: return OfficialRelay | |
| 51 | 新增: } | |
| 52 | 新增: return p.Relay | |
| 53 | 新增:} | |
| 54 | 新增:func pairPin(pin string) bool { | |
| 55 | 新增: b, e := base64.StdEncoding.DecodeString(strings.TrimPrefix(pin, "sha256:")) | |
| 56 | 新增: return e == nil && len(b) == 32 && pin == "sha256:"+base64.StdEncoding.EncodeToString(b) | |
| 57 | 新增:} | |
| 58 | 新增:func (p PairCode) identity() (*remotelink.Identity, error) { | |
| 59 | 新增: if len(p.Seed) != ed25519.SeedSize || !pairPin(p.Host) || !validCapability(p.Room) || !validCapability(p.Token) || !time.Now().Before(time.Unix(p.Expires, 0)) { | |
| 60 | 新增: return nil, errors.New("配对码无效或已过期") | |
| 61 | 新增: } | |
| 62 | 新增: return remotelink.IdentityFromKey(ed25519.NewKeyFromSeed(p.Seed)) | |
| 63 | 新增:} | |
| 64 | 新增:func pairDeadline(ctx context.Context, c *tls.Conn) func() { | |
| 65 | 新增: deadline, _ := ctx.Deadline() | |
| 66 | 新增: _ = c.SetDeadline(deadline) | |
| 67 | 新增: stop := context.AfterFunc(ctx, func() { c.NetConn().Close() }) | |
| 68 | 新增: return func() { stop(); c.NetConn().Close() } | |
| 69 | 新增:} | |
| 70 | 新增: | |
| 71 | 新增:// AcceptPair registers a single phone over a dedicated bootstrap tunnel. The | |
| 72 | 新增:// regular workbench tunnel accepts only the phone's hardware-backed identity. | |
| 73 | 新增:func AcceptPair(ctx context.Context, p PairCode, hostToken string, host *remotelink.Identity, save func(string) (PairedHost, error)) error { | |
| 74 | 新增: temp, err := p.identity() | |
| 75 | 新增: if err != nil { | |
| 76 | 新增: return err | |
| 77 | 新增: } | |
| 78 | 新增: ws, err := join(ctx, p.origin(), p.Room, "host", hostToken) | |
| 79 | 新增: if err != nil { | |
| 80 | 新增: return err | |
| 81 | 新增: } | |
| 82 | 新增: conn, err := remotelink.ServerAfterJoin(ctx, ws, host, temp.Pin) | |
| 83 | 新增: if err != nil { | |
| 84 | 新增: return err | |
| 85 | 新增: } | |
| 86 | 新增: defer pairDeadline(ctx, conn)() | |
| 87 | 新增: var pin string | |
| 88 | 新增: if err = json.NewDecoder(io.LimitReader(conn, 256)).Decode(&pin); err != nil || !pairPin(pin) { | |
| 89 | 新增: return errors.New("手机身份无效") | |
| 90 | 新增: } | |
| 91 | 新增: record, err := save(pin) | |
| 92 | 新增: if err != nil { | |
| 93 | 新增: return err | |
| 94 | 新增: } | |
| 95 | 新增: return json.NewEncoder(conn).Encode(record) | |
| 96 | 新增:} | |
| 97 | 新增:func RedeemPair(ctx context.Context, raw, selectedRelay, phonePin string) (string, error) { | |
| 98 | 新增: var p PairCode | |
| 99 | 新增: raw = strings.TrimSpace(raw) | |
| 100 | 新增: if len(raw) <= 4096 && strings.HasPrefix(raw, "CAGE-") { | |
| 101 | 新增: b, err := base64.RawURLEncoding.DecodeString(raw[5:]) | |
| 102 | 新增: if err != nil { | |
| 103 | 新增: return "", errors.New("配对码格式无效") | |
| 104 | 新增: } | |
| 105 | 新增: raw = string(b) | |
| 106 | 新增: } | |
| 107 | 新增: if len(raw) > 4096 || !strings.HasPrefix(raw, "CAGE1:") || json.Unmarshal([]byte(raw[6:]), &p) != nil || !pairPin(phonePin) { | |
| 108 | 新增: return "", errors.New("请扫描 Cage 电脑端的配对码") | |
| 109 | 新增: } | |
| 110 | 新增: if p.origin() != selectedRelay || !ValidRelayOrigin(selectedRelay) { | |
| 111 | 新增: return "", errors.New("中继与当前设置不符,请检查自建中继地址") | |
| 112 | 新增: } | |
| 113 | 新增: id, err := p.identity() | |
| 114 | 新增: if err != nil { | |
| 115 | 新增: return "", err | |
| 116 | 新增: } | |
| 117 | 新增: ctx, cancel := context.WithDeadline(ctx, time.Unix(p.Expires, 0)) | |
| 118 | 新增: defer cancel() | |
| 119 | 新增: ws, err := join(ctx, selectedRelay, p.Room, "client", p.Token) | |
| 120 | 新增: if err != nil { | |
| 121 | 新增: return "", err | |
| 122 | 新增: } | |
| 123 | 新增: conn, err := remotelink.Client(ctx, ws, id, p.Host) | |
| 124 | 新增: if err != nil { | |
| 125 | 新增: return "", err | |
| 126 | 新增: } | |
| 127 | 新增: defer pairDeadline(ctx, conn)() | |
| 128 | 新增: if err = json.NewEncoder(conn).Encode(phonePin); err != nil { | |
| 129 | 新增: return "", err | |
| 130 | 新增: } | |
| 131 | 新增: var record PairedHost | |
| 132 | 新增: if json.NewDecoder(io.LimitReader(conn, 4096)).Decode(&record) != nil || record.Version != 1 || record.HostPin != p.Host || record.Relay != selectedRelay || !validCapability(record.Lookup) { | |
| 133 | 新增: return "", errors.New("电脑未完成配对,请刷新二维码") | |
| 134 | 新增: } | |
| 135 | 新增: b, err := json.Marshal(record) | |
| 136 | 新增: return string(b), err | |
| 137 | 新增:} | |
| @@ -0,0 +1,79 @@ | ||
| 1 | 新增:package mobilelink | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "net/http/httptest" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "testing" | |
| 9 | 新增: "time" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/sylvinus/agent-vm/internal/relay" | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/remotelink" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:func TestScanEnrollsOnlyHolderOfOriginalCode(t *testing.T) { | |
| 16 | 新增: const admin = "private-test-credential-for-custom-relay" | |
| 17 | 新增: service, err := relay.New(relay.Config{AdminToken: admin}) | |
| 18 | 新增: if err != nil { | |
| 19 | 新增: t.Fatal(err) | |
| 20 | 新增: } | |
| 21 | 新增: edge := httptest.NewServer(service) | |
| 22 | 新增: defer edge.Close() | |
| 23 | 新增: defer service.Close() | |
| 24 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | |
| 25 | 新增: defer cancel() | |
| 26 | 新增: desktop, err := remotelink.NewIdentity() | |
| 27 | 新增: if err != nil { | |
| 28 | 新增: t.Fatal(err) | |
| 29 | 新增: } | |
| 30 | 新增: phone, err := remotelink.NewIdentity() | |
| 31 | 新增: if err != nil { | |
| 32 | 新增: t.Fatal(err) | |
| 33 | 新增: } | |
| 34 | 新增: for _, tampered := range []bool{true, false} { | |
| 35 | 新增: room, err := CreateRoom(ctx, edge.URL, admin) | |
| 36 | 新增: if err != nil { | |
| 37 | 新增: t.Fatal(err) | |
| 38 | 新增: } | |
| 39 | 新增: code, raw, err := NewPairCode(edge.URL, room, desktop.Pin) | |
| 40 | 新增: if err != nil { | |
| 41 | 新增: t.Fatal(err) | |
| 42 | 新增: } | |
| 43 | 新增: done := make(chan error, 1) | |
| 44 | 新增: var enrolled string | |
| 45 | 新增: go func() { | |
| 46 | 新增: done <- AcceptPair(ctx, code, room.HostToken, desktop, func(pin string) (PairedHost, error) { | |
| 47 | 新增: enrolled = pin | |
| 48 | 新增: return PairedHost{1, edge.URL, desktop.Pin, strings.Repeat("A", 43)}, nil | |
| 49 | 新增: }) | |
| 50 | 新增: }() | |
| 51 | 新增: if _, err := RedeemPair(ctx, raw, OfficialRelay, phone.Pin); err == nil { | |
| 52 | 新增: t.Fatal("accepted unexpected relay") | |
| 53 | 新增: } | |
| 54 | 新增: if tampered { | |
| 55 | 新增: changed := code | |
| 56 | 新增: changed.Seed = append([]byte(nil), code.Seed...) | |
| 57 | 新增: changed.Seed[0] ^= 1 | |
| 58 | 新增: payload, _ := json.Marshal(changed) | |
| 59 | 新增: raw = "CAGE1:" + string(payload) | |
| 60 | 新增: } | |
| 61 | 新增: got, clientErr := RedeemPair(ctx, raw, edge.URL, phone.Pin) | |
| 62 | 新增: hostErr := <-done | |
| 63 | 新增: if tampered { | |
| 64 | 新增: if enrolled != "" || hostErr == nil || clientErr == nil { | |
| 65 | 新增: t.Fatal("modified optical secret enrolled a device") | |
| 66 | 新增: } | |
| 67 | 新增: continue | |
| 68 | 新增: } | |
| 69 | 新增: var saved PairedHost | |
| 70 | 新增: if hostErr != nil || clientErr != nil || enrolled != phone.Pin || json.Unmarshal([]byte(got), &saved) != nil || saved.HostPin != desktop.Pin { | |
| 71 | 新增: t.Fatal("valid optical pairing failed", hostErr, clientErr) | |
| 72 | 新增: } | |
| 73 | 新增: expired := code | |
| 74 | 新增: expired.Expires = time.Now().Add(-time.Second).Unix() | |
| 75 | 新增: if _, err = expired.identity(); err == nil { | |
| 76 | 新增: t.Fatal("expired optical pairing accepted") | |
| 77 | 新增: } | |
| 78 | 新增: } | |
| 79 | 新增:} | |
| @@ -0,0 +1,393 @@ | ||
| 1 | 新增:// Package relay pairs two outbound WebSocket connections. It forwards opaque | |
| 2 | 新增:// bytes only; peer identity and application authorization belong to the hosts. | |
| 3 | 新增:package relay | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "crypto/rand" | |
| 7 | 新增: "crypto/sha256" | |
| 8 | 新增: "crypto/subtle" | |
| 9 | 新增: "encoding/base64" | |
| 10 | 新增: "encoding/hex" | |
| 11 | 新增: "encoding/json" | |
| 12 | 新增: "errors" | |
| 13 | 新增: "io" | |
| 14 | 新增: "net/http" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "sync" | |
| 17 | 新增: "time" | |
| 18 | 新增: | |
| 19 | 新增: "github.com/gorilla/websocket" | |
| 20 | 新增:) | |
| 21 | 新增: | |
| 22 | 新增:const MaxFrameSize = 64 << 10 | |
| 23 | 新增: | |
| 24 | 新增:type Config struct { | |
| 25 | 新增: PublicRooms bool | |
| 26 | 新增: AdminToken string | |
| 27 | 新增: MaxRooms int | |
| 28 | 新增: PairTimeout time.Duration | |
| 29 | 新增: IdleTimeout time.Duration | |
| 30 | 新增:} | |
| 31 | 新增: | |
| 32 | 新增:// Invitation contains short-lived transport capabilities, not device identity. | |
| 33 | 新增:// A client must authenticate its peer inside the tunnel before sending data. | |
| 34 | 新增:type Invitation struct { | |
| 35 | 新增: ID string `json:"id"` | |
| 36 | 新增: HostToken string `json:"host_token"` | |
| 37 | 新增: ClientToken string `json:"client_token"` | |
| 38 | 新增: ExpiresAt time.Time `json:"expires_at"` | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:type endpoint struct { | |
| 42 | 新增: token [32]byte | |
| 43 | 新增: claimed bool | |
| 44 | 新增: socket *websocket.Conn | |
| 45 | 新增:} | |
| 46 | 新增: | |
| 47 | 新增:type room struct { | |
| 48 | 新增: id string | |
| 49 | 新增: expiresAt time.Time | |
| 50 | 新增: host endpoint | |
| 51 | 新增: client endpoint | |
| 52 | 新增: ready chan struct{} | |
| 53 | 新增: done chan struct{} | |
| 54 | 新增: timer *time.Timer | |
| 55 | 新增: paired bool | |
| 56 | 新增: lastActivity time.Time | |
| 57 | 新增: lookupHash [32]byte | |
| 58 | 新增: discoverable bool | |
| 59 | 新增: clientInvitation string | |
| 60 | 新增:} | |
| 61 | 新增: | |
| 62 | 新增:type Server struct { | |
| 63 | 新增: config Config | |
| 64 | 新增: admin [32]byte | |
| 65 | 新增: mu sync.Mutex | |
| 66 | 新增: rooms map[string]*room | |
| 67 | 新增: slots map[[32]byte]*room | |
| 68 | 新增: closed bool | |
| 69 | 新增:} | |
| 70 | 新增: | |
| 71 | 新增:func New(config Config) (*Server, error) { | |
| 72 | 新增: if len(config.AdminToken) < 32 || strings.ContainsAny(config.AdminToken, " \t\r\n") { | |
| 73 | 新增: return nil, errors.New("relay admin token must contain at least 32 bytes without whitespace") | |
| 74 | 新增: } | |
| 75 | 新增: if config.MaxRooms == 0 { | |
| 76 | 新增: config.MaxRooms = 128 | |
| 77 | 新增: } | |
| 78 | 新增: if config.PairTimeout == 0 { | |
| 79 | 新增: config.PairTimeout = 2 * time.Minute | |
| 80 | 新增: } | |
| 81 | 新增: if config.IdleTimeout == 0 { | |
| 82 | 新增: config.IdleTimeout = 5 * time.Minute | |
| 83 | 新增: } | |
| 84 | 新增: if config.MaxRooms < 1 || config.PairTimeout < 0 || config.IdleTimeout < 0 { | |
| 85 | 新增: return nil, errors.New("relay limits must be positive") | |
| 86 | 新增: } | |
| 87 | 新增: admin := sha256.Sum256([]byte(config.AdminToken)) | |
| 88 | 新增: config.AdminToken = "" | |
| 89 | 新增: return &Server{config: config, admin: admin, rooms: make(map[string]*room), slots: make(map[[32]byte]*room)}, nil | |
| 90 | 新增:} | |
| 91 | 新增: | |
| 92 | 新增:func secret() string { | |
| 93 | 新增: var value [32]byte | |
| 94 | 新增: _, _ = rand.Read(value[:]) // crypto/rand.Read always fills the buffer or terminates. | |
| 95 | 新增: return base64.RawURLEncoding.EncodeToString(value[:]) | |
| 96 | 新增:} | |
| 97 | 新增: | |
| 98 | 新增:func authorized(r *http.Request, expected [32]byte) bool { | |
| 99 | 新增: values := r.Header.Values("Authorization") | |
| 100 | 新增: if len(values) != 1 || !strings.HasPrefix(values[0], "Bearer ") { | |
| 101 | 新增: return false | |
| 102 | 新增: } | |
| 103 | 新增: value := strings.TrimPrefix(values[0], "Bearer ") | |
| 104 | 新增: if value == "" || strings.ContainsAny(value, " \t\r\n") { | |
| 105 | 新增: return false | |
| 106 | 新增: } | |
| 107 | 新增: actual := sha256.Sum256([]byte(value)) | |
| 108 | 新增: return subtle.ConstantTimeCompare(actual[:], expected[:]) == 1 | |
| 109 | 新增:} | |
| 110 | 新增: | |
| 111 | 新增:func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
| 112 | 新增: w.Header().Set("Cache-Control", "no-store") | |
| 113 | 新增: w.Header().Set("X-Content-Type-Options", "nosniff") | |
| 114 | 新增: // Transport credentials only travel in headers. No browser-origin clients | |
| 115 | 新增: // are accepted: the mobile native transport owns the TLS tunnel. | |
| 116 | 新增: if r.URL.RawQuery != "" || r.Header.Get("Origin") != "" { | |
| 117 | 新增: http.Error(w, "unsupported request", http.StatusBadRequest) | |
| 118 | 新增: return | |
| 119 | 新增: } | |
| 120 | 新增: if r.Method == http.MethodGet && r.URL.Path == "/healthz" { | |
| 121 | 新增: s.mu.Lock() | |
| 122 | 新增: closed := s.closed | |
| 123 | 新增: s.mu.Unlock() | |
| 124 | 新增: if closed { | |
| 125 | 新增: http.Error(w, "stopping", http.StatusServiceUnavailable) | |
| 126 | 新增: return | |
| 127 | 新增: } | |
| 128 | 新增: _, _ = w.Write([]byte("ok\n")) | |
| 129 | 新增: return | |
| 130 | 新增: } | |
| 131 | 新增: if r.Method == http.MethodPost && r.URL.Path == "/v1/rooms" { | |
| 132 | 新增: s.create(w, r) | |
| 133 | 新增: return | |
| 134 | 新增: } | |
| 135 | 新增: if r.Method == http.MethodGet && r.URL.Path == "/v1/invitation" { | |
| 136 | 新增: s.lookup(w, r) | |
| 137 | 新增: return | |
| 138 | 新增: } | |
| 139 | 新增: parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/") | |
| 140 | 新增: if r.Method == http.MethodGet && len(parts) == 4 && parts[0] == "v1" && parts[1] == "rooms" && (parts[3] == "host" || parts[3] == "client") { | |
| 141 | 新增: s.join(w, r, parts[2], parts[3]) | |
| 142 | 新增: return | |
| 143 | 新增: } | |
| 144 | 新增: http.NotFound(w, r) | |
| 145 | 新增:} | |
| 146 | 新增: | |
| 147 | 新增:func (s *Server) create(w http.ResponseWriter, r *http.Request) { | |
| 148 | 新增: if !(s.config.PublicRooms && len(r.Header.Values("Authorization")) == 0) && !authorized(r, s.admin) { | |
| 149 | 新增: http.Error(w, "unauthorized", http.StatusUnauthorized) | |
| 150 | 新增: return | |
| 151 | 新增: } | |
| 152 | 新增: var hash [32]byte | |
| 153 | 新增: discoverable := r.ContentLength != 0 | |
| 154 | 新增: if discoverable { | |
| 155 | 新增: var body struct { | |
| 156 | 新增: Hash string `json:"lookup_hash"` | |
| 157 | 新增: } | |
| 158 | 新增: decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256)) | |
| 159 | 新增: decoder.DisallowUnknownFields() | |
| 160 | 新增: if decoder.Decode(&body) != nil || decoder.Decode(new(any)) != io.EOF { | |
| 161 | 新增: http.Error(w, "invalid room registration", http.StatusBadRequest) | |
| 162 | 新增: return | |
| 163 | 新增: } | |
| 164 | 新增: digest, err := hex.DecodeString(body.Hash) | |
| 165 | 新增: if err != nil || len(digest) != len(hash) || hex.EncodeToString(digest) != body.Hash { | |
| 166 | 新增: http.Error(w, "invalid room registration", http.StatusBadRequest) | |
| 167 | 新增: return | |
| 168 | 新增: } | |
| 169 | 新增: copy(hash[:], digest) | |
| 170 | 新增: } | |
| 171 | 新增: s.mu.Lock() | |
| 172 | 新增: if s.closed { | |
| 173 | 新增: s.mu.Unlock() | |
| 174 | 新增: http.Error(w, "stopping", http.StatusServiceUnavailable) | |
| 175 | 新增: return | |
| 176 | 新增: } | |
| 177 | 新增: if len(s.rooms) >= s.config.MaxRooms { | |
| 178 | 新增: s.mu.Unlock() | |
| 179 | 新增: http.Error(w, "relay capacity reached", http.StatusTooManyRequests) | |
| 180 | 新增: return | |
| 181 | 新增: } | |
| 182 | 新增: if discoverable && s.slots[hash] != nil { | |
| 183 | 新增: s.mu.Unlock() | |
| 184 | 新增: http.Error(w, "existing device connection", http.StatusConflict) | |
| 185 | 新增: return | |
| 186 | 新增: } | |
| 187 | 新增: i := Invitation{ID: secret(), HostToken: secret(), ClientToken: secret(), ExpiresAt: time.Now().Add(s.config.PairTimeout)} | |
| 188 | 新增: room := &room{id: i.ID, expiresAt: i.ExpiresAt, host: endpoint{token: sha256.Sum256([]byte(i.HostToken))}, | |
| 189 | 新增: client: endpoint{token: sha256.Sum256([]byte(i.ClientToken))}, ready: make(chan struct{}), done: make(chan struct{})} | |
| 190 | 新增: s.rooms[i.ID] = room | |
| 191 | 新增: if discoverable { | |
| 192 | 新增: room.lookupHash, room.discoverable, room.clientInvitation = hash, true, i.ClientToken | |
| 193 | 新增: s.slots[hash] = room | |
| 194 | 新增: } | |
| 195 | 新增: room.timer = time.AfterFunc(s.config.PairTimeout, func() { s.expire(room) }) | |
| 196 | 新增: s.mu.Unlock() | |
| 197 | 新增: w.Header().Set("Content-Type", "application/json") | |
| 198 | 新增: w.WriteHeader(http.StatusCreated) | |
| 199 | 新增: _ = json.NewEncoder(w).Encode(i) | |
| 200 | 新增:} | |
| 201 | 新增: | |
| 202 | 新增:// A saved device resolves a fresh transport ticket. Both device certificates | |
| 203 | 新增:// are still independently verified end-to-end when it uses that ticket. | |
| 204 | 新增:func (s *Server) lookup(w http.ResponseWriter, r *http.Request) { | |
| 205 | 新增: values := r.Header.Values("Authorization") | |
| 206 | 新增: if len(values) != 1 { | |
| 207 | 新增: http.NotFound(w, r) | |
| 208 | 新增: return | |
| 209 | 新增: } | |
| 210 | 新增: value, ok := strings.CutPrefix(values[0], "Bearer ") | |
| 211 | 新增: key, err := base64.RawURLEncoding.DecodeString(value) | |
| 212 | 新增: if !ok || err != nil || len(key) != 32 || base64.RawURLEncoding.EncodeToString(key) != value { | |
| 213 | 新增: http.NotFound(w, r) | |
| 214 | 新增: return | |
| 215 | 新增: } | |
| 216 | 新增: hash := sha256.Sum256(key) | |
| 217 | 新增: clear(key) | |
| 218 | 新增: s.mu.Lock() | |
| 219 | 新增: room := s.slots[hash] | |
| 220 | 新增: if room == nil || room.host.socket == nil || room.client.claimed || !time.Now().Before(room.expiresAt) { | |
| 221 | 新增: s.mu.Unlock() | |
| 222 | 新增: http.NotFound(w, r) | |
| 223 | 新增: return | |
| 224 | 新增: } | |
| 225 | 新增: response := struct { | |
| 226 | 新增: ID string `json:"id"` | |
| 227 | 新增: Token string `json:"client_token"` | |
| 228 | 新增: ExpiresAt time.Time `json:"expires_at"` | |
| 229 | 新增: }{room.id, room.clientInvitation, room.expiresAt} | |
| 230 | 新增: s.mu.Unlock() | |
| 231 | 新增: w.Header().Set("Content-Type", "application/json") | |
| 232 | 新增: _ = json.NewEncoder(w).Encode(response) | |
| 233 | 新增:} | |
| 234 | 新增: | |
| 235 | 新增:func (s *Server) join(w http.ResponseWriter, r *http.Request, id, role string) { | |
| 236 | 新增: s.mu.Lock() | |
| 237 | 新增: room := s.rooms[id] | |
| 238 | 新增: if room == nil || s.closed { | |
| 239 | 新增: s.mu.Unlock() | |
| 240 | 新增: http.Error(w, "connection unavailable", http.StatusNotFound) | |
| 241 | 新增: return | |
| 242 | 新增: } | |
| 243 | 新增: endpoint := &room.client | |
| 244 | 新增: if role == "host" { | |
| 245 | 新增: endpoint = &room.host | |
| 246 | 新增: } | |
| 247 | 新增: if !authorized(r, endpoint.token) { | |
| 248 | 新增: s.mu.Unlock() | |
| 249 | 新增: http.Error(w, "unauthorized", http.StatusUnauthorized) | |
| 250 | 新增: return | |
| 251 | 新增: } | |
| 252 | 新增: if endpoint.claimed || room.paired || !time.Now().Before(room.expiresAt) { | |
| 253 | 新增: s.mu.Unlock() | |
| 254 | 新增: http.Error(w, "connection invitation consumed or expired", http.StatusConflict) | |
| 255 | 新增: return | |
| 256 | 新增: } | |
| 257 | 新增: endpoint.claimed = true | |
| 258 | 新增: s.mu.Unlock() | |
| 259 | 新增: defer s.remove(room) | |
| 260 | 新增: | |
| 261 | 新增: upgrader := websocket.Upgrader{HandshakeTimeout: 5 * time.Second, CheckOrigin: func(r *http.Request) bool { return r.Header.Get("Origin") == "" }} | |
| 262 | 新增: connection, err := upgrader.Upgrade(w, r, nil) | |
| 263 | 新增: if err != nil { | |
| 264 | 新增: return | |
| 265 | 新增: } | |
| 266 | 新增: defer connection.Close() | |
| 267 | 新增: connection.SetReadLimit(MaxFrameSize) | |
| 268 | 新增: s.mu.Lock() | |
| 269 | 新增: if s.rooms[id] != room || s.closed { | |
| 270 | 新增: s.mu.Unlock() | |
| 271 | 新增: return | |
| 272 | 新增: } | |
| 273 | 新增: endpoint.socket = connection | |
| 274 | 新增: if room.host.socket != nil && room.client.socket != nil { | |
| 275 | 新增: room.paired = true | |
| 276 | 新增: room.clientInvitation = "" | |
| 277 | 新增: room.timer.Stop() | |
| 278 | 新增: room.lastActivity = time.Now() | |
| 279 | 新增: room.timer = time.AfterFunc(s.config.IdleTimeout, func() { s.expireIdle(room) }) | |
| 280 | 新增: close(room.ready) | |
| 281 | 新增: } | |
| 282 | 新增: s.mu.Unlock() | |
| 283 | 新增: | |
| 284 | 新增: // Read even before the peer joins. A waiting host can disconnect on | |
| 285 | 新增: // restart, and its saved pairing must immediately be free to register again. | |
| 286 | 新增: var other *websocket.Conn | |
| 287 | 新增: for { | |
| 288 | 新增: kind, data, err := connection.ReadMessage() | |
| 289 | 新增: if err != nil || kind != websocket.BinaryMessage { | |
| 290 | 新增: return | |
| 291 | 新增: } | |
| 292 | 新增: if other == nil { | |
| 293 | 新增: select { | |
| 294 | 新增: case <-room.ready: | |
| 295 | 新增: case <-room.done: | |
| 296 | 新增: return | |
| 297 | 新增: } | |
| 298 | 新增: s.mu.Lock() | |
| 299 | 新增: other = room.host.socket | |
| 300 | 新增: if role == "host" { | |
| 301 | 新增: other = room.client.socket | |
| 302 | 新增: } | |
| 303 | 新增: s.mu.Unlock() | |
| 304 | 新增: } | |
| 305 | 新增: s.mu.Lock() | |
| 306 | 新增: live := s.rooms[room.id] == room | |
| 307 | 新增: if live { | |
| 308 | 新增: room.lastActivity = time.Now() | |
| 309 | 新增: } | |
| 310 | 新增: s.mu.Unlock() | |
| 311 | 新增: if !live { | |
| 312 | 新增: return | |
| 313 | 新增: } | |
| 314 | 新增: _ = other.SetWriteDeadline(time.Now().Add(10 * time.Second)) | |
| 315 | 新增: if err := other.WriteMessage(websocket.BinaryMessage, data); err != nil { | |
| 316 | 新增: return | |
| 317 | 新增: } | |
| 318 | 新增: } | |
| 319 | 新增:} | |
| 320 | 新增: | |
| 321 | 新增:// A receive-only client is active while the host streams output. Account for | |
| 322 | 新增:// traffic in either direction instead of timing out the quieter endpoint. | |
| 323 | 新增:func (s *Server) expireIdle(room *room) { | |
| 324 | 新增: s.mu.Lock() | |
| 325 | 新增: if s.rooms[room.id] != room { | |
| 326 | 新增: s.mu.Unlock() | |
| 327 | 新增: return | |
| 328 | 新增: } | |
| 329 | 新增: remaining := time.Until(room.lastActivity.Add(s.config.IdleTimeout)) | |
| 330 | 新增: if remaining > 0 { | |
| 331 | 新增: room.timer.Reset(remaining) | |
| 332 | 新增: s.mu.Unlock() | |
| 333 | 新增: return | |
| 334 | 新增: } | |
| 335 | 新增: connections := s.removeLocked(room) | |
| 336 | 新增: s.mu.Unlock() | |
| 337 | 新增: closeConnections(connections) | |
| 338 | 新增:} | |
| 339 | 新增: | |
| 340 | 新增:// expire only removes waiting rooms; active connections have an idle timeout. | |
| 341 | 新增:func (s *Server) expire(room *room) { | |
| 342 | 新增: s.mu.Lock() | |
| 343 | 新增: if s.rooms[room.id] != room || room.paired { | |
| 344 | 新增: s.mu.Unlock() | |
| 345 | 新增: return | |
| 346 | 新增: } | |
| 347 | 新增: connections := s.removeLocked(room) | |
| 348 | 新增: s.mu.Unlock() | |
| 349 | 新增: closeConnections(connections) | |
| 350 | 新增:} | |
| 351 | 新增: | |
| 352 | 新增:func (s *Server) removeLocked(room *room) []*websocket.Conn { | |
| 353 | 新增: if s.rooms[room.id] != room { | |
| 354 | 新增: return nil | |
| 355 | 新增: } | |
| 356 | 新增: delete(s.rooms, room.id) | |
| 357 | 新增: if room.discoverable { | |
| 358 | 新增: delete(s.slots, room.lookupHash) | |
| 359 | 新增: room.clientInvitation = "" | |
| 360 | 新增: } | |
| 361 | 新增: room.timer.Stop() | |
| 362 | 新增: close(room.done) | |
| 363 | 新增: return []*websocket.Conn{room.host.socket, room.client.socket} | |
| 364 | 新增:} | |
| 365 | 新增: | |
| 366 | 新增:func closeConnections(connections []*websocket.Conn) { | |
| 367 | 新增: for _, connection := range connections { | |
| 368 | 新增: if connection != nil { | |
| 369 | 新增: _ = connection.Close() | |
| 370 | 新增: } | |
| 371 | 新增: } | |
| 372 | 新增:} | |
| 373 | 新增: | |
| 374 | 新增:func (s *Server) remove(room *room) { | |
| 375 | 新增: s.mu.Lock() | |
| 376 | 新增: connections := s.removeLocked(room) | |
| 377 | 新增: s.mu.Unlock() | |
| 378 | 新增: closeConnections(connections) | |
| 379 | 新增:} | |
| 380 | 新增: | |
| 381 | 新增:// Close rejects new rooms and closes all upgraded connections. HTTP shutdown | |
| 382 | 新增:// alone does not close hijacked WebSockets; callers must also call Close. | |
| 383 | 新增:func (s *Server) Close() error { | |
| 384 | 新增: s.mu.Lock() | |
| 385 | 新增: s.closed = true | |
| 386 | 新增: var connections []*websocket.Conn | |
| 387 | 新增: for _, room := range s.rooms { | |
| 388 | 新增: connections = append(connections, s.removeLocked(room)...) | |
| 389 | 新增: } | |
| 390 | 新增: s.mu.Unlock() | |
| 391 | 新增: closeConnections(connections) | |
| 392 | 新增: return nil | |
| 393 | 新增:} | |
| @@ -0,0 +1,345 @@ | ||
| 1 | 新增:package relay | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "crypto/rand" | |
| 6 | 新增: "crypto/sha256" | |
| 7 | 新增: "encoding/base64" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "fmt" | |
| 10 | 新增: "io" | |
| 11 | 新增: "net/http" | |
| 12 | 新增: "net/http/httptest" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "testing" | |
| 15 | 新增: "time" | |
| 16 | 新增: | |
| 17 | 新增: "github.com/gorilla/websocket" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:const testAdmin = "relay-test-admin-token-not-a-real-credential" | |
| 21 | 新增: | |
| 22 | 新增:func testServer(t *testing.T, config Config) (*Server, *httptest.Server) { | |
| 23 | 新增: t.Helper() | |
| 24 | 新增: config.AdminToken = testAdmin | |
| 25 | 新增: s, err := New(config) | |
| 26 | 新增: if err != nil { | |
| 27 | 新增: t.Fatal(err) | |
| 28 | 新增: } | |
| 29 | 新增: httpServer := httptest.NewServer(s) | |
| 30 | 新增: t.Cleanup(func() { _ = s.Close(); httpServer.Close() }) | |
| 31 | 新增: return s, httpServer | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:func createRoom(t *testing.T, serverURL, token string, expectedStatus int) Invitation { | |
| 35 | 新增: t.Helper() | |
| 36 | 新增: r, err := http.NewRequest(http.MethodPost, serverURL+"/v1/rooms", nil) | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: t.Fatal(err) | |
| 39 | 新增: } | |
| 40 | 新增: r.Header.Set("Authorization", "Bearer "+token) | |
| 41 | 新增: response, err := http.DefaultClient.Do(r) | |
| 42 | 新增: if err != nil { | |
| 43 | 新增: t.Fatal(err) | |
| 44 | 新增: } | |
| 45 | 新增: defer response.Body.Close() | |
| 46 | 新增: if response.StatusCode != expectedStatus { | |
| 47 | 新增: t.Fatalf("create status = %d, want %d", response.StatusCode, expectedStatus) | |
| 48 | 新增: } | |
| 49 | 新增: var invitation Invitation | |
| 50 | 新增: if expectedStatus == http.StatusCreated { | |
| 51 | 新增: if err := json.NewDecoder(response.Body).Decode(&invitation); err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: } | |
| 55 | 新增: return invitation | |
| 56 | 新增:} | |
| 57 | 新增: | |
| 58 | 新增:func dial(t *testing.T, serverURL string, invitation Invitation, role, token string, expectedStatus int) *websocket.Conn { | |
| 59 | 新增: t.Helper() | |
| 60 | 新增: url := "ws" + strings.TrimPrefix(serverURL, "http") + "/v1/rooms/" + invitation.ID + "/" + role | |
| 61 | 新增: connection, response, err := websocket.DefaultDialer.Dial(url, http.Header{"Authorization": {"Bearer " + token}}) | |
| 62 | 新增: if expectedStatus == http.StatusSwitchingProtocols { | |
| 63 | 新增: if err != nil { | |
| 64 | 新增: t.Fatalf("connect: %v", err) | |
| 65 | 新增: } | |
| 66 | 新增: t.Cleanup(func() { _ = connection.Close() }) | |
| 67 | 新增: return connection | |
| 68 | 新增: } | |
| 69 | 新增: if connection != nil { | |
| 70 | 新增: _ = connection.Close() | |
| 71 | 新增: t.Fatal("unexpected accepted connection") | |
| 72 | 新增: } | |
| 73 | 新增: if err == nil || response == nil || response.StatusCode != expectedStatus { | |
| 74 | 新增: t.Fatalf("rejected connect: response=%v, err=%v, want status %d", response, err, expectedStatus) | |
| 75 | 新增: } | |
| 76 | 新增: _ = response.Body.Close() | |
| 77 | 新增: return nil | |
| 78 | 新增:} | |
| 79 | 新增: | |
| 80 | 新增:func read(t *testing.T, connection *websocket.Conn, expected []byte) { | |
| 81 | 新增: t.Helper() | |
| 82 | 新增: _ = connection.SetReadDeadline(time.Now().Add(2 * time.Second)) | |
| 83 | 新增: kind, actual, err := connection.ReadMessage() | |
| 84 | 新增: if err != nil || kind != websocket.BinaryMessage || !bytes.Equal(actual, expected) { | |
| 85 | 新增: t.Fatalf("roundtrip kind=%d payload length=%d err=%v", kind, len(actual), err) | |
| 86 | 新增: } | |
| 87 | 新增:} | |
| 88 | 新增: | |
| 89 | 新增:func waitClosed(t *testing.T, connection *websocket.Conn) { | |
| 90 | 新增: t.Helper() | |
| 91 | 新增: _ = connection.SetReadDeadline(time.Now().Add(2 * time.Second)) | |
| 92 | 新增: if _, _, err := connection.ReadMessage(); err == nil { | |
| 93 | 新增: t.Fatal("connection remained readable") | |
| 94 | 新增: } else if timeout, ok := err.(interface{ Timeout() bool }); ok && timeout.Timeout() { | |
| 95 | 新增: t.Fatal("server did not actively close connection") | |
| 96 | 新增: } | |
| 97 | 新增:} | |
| 98 | 新增: | |
| 99 | 新增:func TestAuthenticatedSingleUsePair(t *testing.T) { | |
| 100 | 新增: _, server := testServer(t, Config{MaxRooms: 1}) | |
| 101 | 新增: createRoom(t, server.URL, "wrong-admin", http.StatusUnauthorized) | |
| 102 | 新增: i := createRoom(t, server.URL, testAdmin, http.StatusCreated) | |
| 103 | 新增: createRoom(t, server.URL, testAdmin, http.StatusTooManyRequests) | |
| 104 | 新增: dial(t, server.URL, i, "host", i.ClientToken, http.StatusUnauthorized) | |
| 105 | 新增: host := dial(t, server.URL, i, "host", i.HostToken, http.StatusSwitchingProtocols) | |
| 106 | 新增: dial(t, server.URL, i, "host", i.HostToken, http.StatusConflict) | |
| 107 | 新增: client := dial(t, server.URL, i, "client", i.ClientToken, http.StatusSwitchingProtocols) | |
| 108 | 新增: for _, pair := range [][2]*websocket.Conn{{host, client}, {client, host}} { | |
| 109 | 新增: payload := bytes.Repeat([]byte{0, 9, 255, 42}, 8192) | |
| 110 | 新增: if err := pair[0].WriteMessage(websocket.BinaryMessage, payload); err != nil { | |
| 111 | 新增: t.Fatal(err) | |
| 112 | 新增: } | |
| 113 | 新增: read(t, pair[1], payload) | |
| 114 | 新增: } | |
| 115 | 新增: _ = client.Close() | |
| 116 | 新增: waitClosed(t, host) | |
| 117 | 新增: dial(t, server.URL, i, "client", i.ClientToken, http.StatusNotFound) | |
| 118 | 新增: createRoom(t, server.URL, testAdmin, http.StatusCreated) | |
| 119 | 新增:} | |
| 120 | 新增: | |
| 121 | 新增:func TestRoomExpiryAndShutdownCloseWaitingSockets(t *testing.T) { | |
| 122 | 新增: for _, shutdown := range []bool{false, true} { | |
| 123 | 新增: t.Run(map[bool]string{false: "expires", true: "shutdown"}[shutdown], func(t *testing.T) { | |
| 124 | 新增: service, server := testServer(t, Config{PairTimeout: 200 * time.Millisecond, MaxRooms: 1}) | |
| 125 | 新增: i := createRoom(t, server.URL, testAdmin, http.StatusCreated) | |
| 126 | 新增: host := dial(t, server.URL, i, "host", i.HostToken, http.StatusSwitchingProtocols) | |
| 127 | 新增: if shutdown { | |
| 128 | 新增: _ = service.Close() | |
| 129 | 新增: } | |
| 130 | 新增: waitClosed(t, host) | |
| 131 | 新增: if shutdown { | |
| 132 | 新增: createRoom(t, server.URL, testAdmin, http.StatusServiceUnavailable) | |
| 133 | 新增: } else { | |
| 134 | 新增: createRoom(t, server.URL, testAdmin, http.StatusCreated) | |
| 135 | 新增: } | |
| 136 | 新增: }) | |
| 137 | 新增: } | |
| 138 | 新增:} | |
| 139 | 新增: | |
| 140 | 新增:func TestDisconnectedWaitingHostReleasesRoom(t *testing.T) { | |
| 141 | 新增: service, server := testServer(t, Config{MaxRooms: 1, PairTimeout: time.Minute}) | |
| 142 | 新增: invite := createRoom(t, server.URL, testAdmin, http.StatusCreated) | |
| 143 | 新增: host := dial(t, server.URL, invite, "host", invite.HostToken, http.StatusSwitchingProtocols) | |
| 144 | 新增: _ = host.Close() | |
| 145 | 新增: deadline := time.Now().Add(2 * time.Second) | |
| 146 | 新增: for { | |
| 147 | 新增: service.mu.Lock() | |
| 148 | 新增: _, stale := service.rooms[invite.ID] | |
| 149 | 新增: service.mu.Unlock() | |
| 150 | 新增: if !stale { | |
| 151 | 新增: break | |
| 152 | 新增: } | |
| 153 | 新增: if time.Now().After(deadline) { | |
| 154 | 新增: t.Fatal("disconnected waiting host still occupies its room") | |
| 155 | 新增: } | |
| 156 | 新增: time.Sleep(10 * time.Millisecond) | |
| 157 | 新增: } | |
| 158 | 新增: createRoom(t, server.URL, testAdmin, http.StatusCreated) | |
| 159 | 新增:} | |
| 160 | 新增: | |
| 161 | 新增:func TestInvalidStreamClosesBothDirections(t *testing.T) { | |
| 162 | 新增: for _, tc := range []struct { | |
| 163 | 新增: name string | |
| 164 | 新增: kind int | |
| 165 | 新增: size int | |
| 166 | 新增: }{{"text", websocket.TextMessage, 10}, {"oversize", websocket.BinaryMessage, MaxFrameSize + 1}} { | |
| 167 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 168 | 新增: _, server := testServer(t, Config{}) | |
| 169 | 新增: i := createRoom(t, server.URL, testAdmin, http.StatusCreated) | |
| 170 | 新增: host := dial(t, server.URL, i, "host", i.HostToken, http.StatusSwitchingProtocols) | |
| 171 | 新增: client := dial(t, server.URL, i, "client", i.ClientToken, http.StatusSwitchingProtocols) | |
| 172 | 新增: _ = client.WriteMessage(tc.kind, make([]byte, tc.size)) | |
| 173 | 新增: waitClosed(t, host) | |
| 174 | 新增: waitClosed(t, client) | |
| 175 | 新增: }) | |
| 176 | 新增: } | |
| 177 | 新增:} | |
| 178 | 新增: | |
| 179 | 新增:func TestActiveIdleTimeoutAndServerClose(t *testing.T) { | |
| 180 | 新增: for _, shutdown := range []bool{false, true} { | |
| 181 | 新增: t.Run(map[bool]string{false: "idle", true: "shutdown"}[shutdown], func(t *testing.T) { | |
| 182 | 新增: service, server := testServer(t, Config{IdleTimeout: 100 * time.Millisecond}) | |
| 183 | 新增: i := createRoom(t, server.URL, testAdmin, http.StatusCreated) | |
| 184 | 新增: host := dial(t, server.URL, i, "host", i.HostToken, http.StatusSwitchingProtocols) | |
| 185 | 新增: client := dial(t, server.URL, i, "client", i.ClientToken, http.StatusSwitchingProtocols) | |
| 186 | 新增: if shutdown { | |
| 187 | 新增: _ = service.Close() | |
| 188 | 新增: } | |
| 189 | 新增: waitClosed(t, host) | |
| 190 | 新增: waitClosed(t, client) | |
| 191 | 新增: }) | |
| 192 | 新增: } | |
| 193 | 新增:} | |
| 194 | 新增: | |
| 195 | 新增:func TestOneWayOutputKeepsRoomAlive(t *testing.T) { | |
| 196 | 新增: _, server := testServer(t, Config{IdleTimeout: 200 * time.Millisecond}) | |
| 197 | 新增: i := createRoom(t, server.URL, testAdmin, http.StatusCreated) | |
| 198 | 新增: host := dial(t, server.URL, i, "host", i.HostToken, http.StatusSwitchingProtocols) | |
| 199 | 新增: client := dial(t, server.URL, i, "client", i.ClientToken, http.StatusSwitchingProtocols) | |
| 200 | 新增: ticker := time.NewTicker(30 * time.Millisecond) | |
| 201 | 新增: defer ticker.Stop() | |
| 202 | 新增: for n := 0; n < 15; n++ { | |
| 203 | 新增: <-ticker.C | |
| 204 | 新增: payload := []byte{byte(n)} | |
| 205 | 新增: if err := host.WriteMessage(websocket.BinaryMessage, payload); err != nil { | |
| 206 | 新增: t.Fatal(err) | |
| 207 | 新增: } | |
| 208 | 新增: read(t, client, payload) | |
| 209 | 新增: } | |
| 210 | 新增: // Once both directions become idle, both peers are actively closed. | |
| 211 | 新增: waitClosed(t, host) | |
| 212 | 新增: waitClosed(t, client) | |
| 213 | 新增:} | |
| 214 | 新增: | |
| 215 | 新增:func TestNoURLCredentialsOrBrowserOrigins(t *testing.T) { | |
| 216 | 新增: _, server := testServer(t, Config{}) | |
| 217 | 新增: for _, tc := range []struct{ path, origin string }{{"/v1/rooms?token=not-secret", ""}, {"/v1/rooms", "https://untrusted.example"}} { | |
| 218 | 新增: r, _ := http.NewRequest(http.MethodPost, server.URL+tc.path, nil) | |
| 219 | 新增: r.Header.Set("Authorization", "Bearer "+testAdmin) | |
| 220 | 新增: r.Header.Set("Origin", tc.origin) | |
| 221 | 新增: response, err := http.DefaultClient.Do(r) | |
| 222 | 新增: if err != nil { | |
| 223 | 新增: t.Fatal(err) | |
| 224 | 新增: } | |
| 225 | 新增: body, _ := io.ReadAll(response.Body) | |
| 226 | 新增: _ = response.Body.Close() | |
| 227 | 新增: if response.StatusCode != http.StatusBadRequest || strings.Contains(string(body), testAdmin) { | |
| 228 | 新增: t.Fatalf("unexpected rejection: %d %q", response.StatusCode, body) | |
| 229 | 新增: } | |
| 230 | 新增: } | |
| 231 | 新增:} | |
| 232 | 新增: | |
| 233 | 新增:func TestSavedDeviceReceivesNewInvitationAfterDisconnect(t *testing.T) { | |
| 234 | 新增: _, server := testServer(t, Config{}) | |
| 235 | 新增: key := make([]byte, 32) | |
| 236 | 新增: if _, err := rand.Read(key); err != nil { | |
| 237 | 新增: t.Fatal(err) | |
| 238 | 新增: } | |
| 239 | 新增: secret := base64.RawURLEncoding.EncodeToString(key) | |
| 240 | 新增: digest := sha256.Sum256(key) | |
| 241 | 新增: body := fmt.Sprintf(`{"lookup_hash":"%x"}`, digest) | |
| 242 | 新增: create := func(status int) Invitation { | |
| 243 | 新增: t.Helper() | |
| 244 | 新增: req, _ := http.NewRequest("POST", server.URL+"/v1/rooms", strings.NewReader(body)) | |
| 245 | 新增: req.Header.Set("Authorization", "Bearer "+testAdmin) | |
| 246 | 新增: res, err := http.DefaultClient.Do(req) | |
| 247 | 新增: if err != nil { | |
| 248 | 新增: t.Fatal(err) | |
| 249 | 新增: } | |
| 250 | 新增: defer res.Body.Close() | |
| 251 | 新增: if res.StatusCode != status { | |
| 252 | 新增: t.Fatalf("room: %d, want %d", res.StatusCode, status) | |
| 253 | 新增: } | |
| 254 | 新增: var i Invitation | |
| 255 | 新增: if status == 201 { | |
| 256 | 新增: if err = json.NewDecoder(res.Body).Decode(&i); err != nil { | |
| 257 | 新增: t.Fatal(err) | |
| 258 | 新增: } | |
| 259 | 新增: } | |
| 260 | 新增: return i | |
| 261 | 新增: } | |
| 262 | 新增: lookup := func(token string) (int, Invitation) { | |
| 263 | 新增: t.Helper() | |
| 264 | 新增: req, _ := http.NewRequest("GET", server.URL+"/v1/invitation", nil) | |
| 265 | 新增: req.Header.Set("Authorization", "Bearer "+token) | |
| 266 | 新增: res, err := http.DefaultClient.Do(req) | |
| 267 | 新增: if err != nil { | |
| 268 | 新增: t.Fatal(err) | |
| 269 | 新增: } | |
| 270 | 新增: defer res.Body.Close() | |
| 271 | 新增: var i Invitation | |
| 272 | 新增: if res.StatusCode == 200 { | |
| 273 | 新增: if err = json.NewDecoder(res.Body).Decode(&i); err != nil { | |
| 274 | 新增: t.Fatal(err) | |
| 275 | 新增: } | |
| 276 | 新增: if i.HostToken != "" || res.Header.Get("Cache-Control") != "no-store" { | |
| 277 | 新增: t.Fatal("lookup exposed a host credential or a cacheable ticket") | |
| 278 | 新增: } | |
| 279 | 新增: } | |
| 280 | 新增: return res.StatusCode, i | |
| 281 | 新增: } | |
| 282 | 新增: first := create(201) | |
| 283 | 新增: if status, _ := lookup(secret); status != 404 { | |
| 284 | 新增: t.Fatal("advertised a room before host joined") | |
| 285 | 新增: } | |
| 286 | 新增: host := dial(t, server.URL, first, "host", first.HostToken, 101) | |
| 287 | 新增: create(409) | |
| 288 | 新增: if status, _ := lookup(base64.RawURLEncoding.EncodeToString(make([]byte, 32))); status != 404 { | |
| 289 | 新增: t.Fatal("unknown device looked up a room") | |
| 290 | 新增: } | |
| 291 | 新增: wait := func(i Invitation) { | |
| 292 | 新增: t.Helper() | |
| 293 | 新增: deadline := time.Now().Add(time.Second) | |
| 294 | 新增: for time.Now().Before(deadline) { | |
| 295 | 新增: status, found := lookup(secret) | |
| 296 | 新增: if status == 200 { | |
| 297 | 新增: if found.ID != i.ID || found.ClientToken != i.ClientToken { | |
| 298 | 新增: t.Fatal("looked up another device or stale ticket") | |
| 299 | 新增: } | |
| 300 | 新增: return | |
| 301 | 新增: } | |
| 302 | 新增: time.Sleep(5 * time.Millisecond) | |
| 303 | 新增: } | |
| 304 | 新增: t.Fatal("room did not become discoverable") | |
| 305 | 新增: } | |
| 306 | 新增: wait(first) | |
| 307 | 新增: client := dial(t, server.URL, first, "client", first.ClientToken, 101) | |
| 308 | 新增: if status, _ := lookup(secret); status != 404 { | |
| 309 | 新增: t.Fatal("claimed client ticket could be fetched") | |
| 310 | 新增: } | |
| 311 | 新增: client.Close() | |
| 312 | 新增: waitClosed(t, host) | |
| 313 | 新增: if status, _ := lookup(secret); status != 404 { | |
| 314 | 新增: t.Fatal("closed room still discoverable") | |
| 315 | 新增: } | |
| 316 | 新增: second := create(201) | |
| 317 | 新增: dial(t, server.URL, second, "host", second.HostToken, 101) | |
| 318 | 新增: if first.ID == second.ID || first.ClientToken == second.ClientToken { | |
| 319 | 新增: t.Fatal("reused a one-time transport credential") | |
| 320 | 新增: } | |
| 321 | 新增: wait(second) | |
| 322 | 新增:} | |
| 323 | 新增: | |
| 324 | 新增:func TestPublicRoomCreationKeepsRoleAuthentication(t *testing.T) { | |
| 325 | 新增: for _, public := range []bool{false, true} { | |
| 326 | 新增: _, server := testServer(t, Config{PublicRooms: public}) | |
| 327 | 新增: response, err := http.Post(server.URL+"/v1/rooms", "application/json", nil) | |
| 328 | 新增: if err != nil { | |
| 329 | 新增: t.Fatal(err) | |
| 330 | 新增: } | |
| 331 | 新增: defer response.Body.Close() | |
| 332 | 新增: if !public { | |
| 333 | 新增: if response.StatusCode != http.StatusUnauthorized { | |
| 334 | 新增: t.Fatal("private relay allowed anonymous room creation") | |
| 335 | 新增: } | |
| 336 | 新增: continue | |
| 337 | 新增: } | |
| 338 | 新增: var room Invitation | |
| 339 | 新增: if response.StatusCode != http.StatusCreated || json.NewDecoder(response.Body).Decode(&room) != nil { | |
| 340 | 新增: t.Fatal("public relay did not create a room") | |
| 341 | 新增: } | |
| 342 | 新增: dial(t, server.URL, room, "client", room.HostToken, http.StatusUnauthorized) | |
| 343 | 新增: dial(t, server.URL, room, "host", room.HostToken, http.StatusSwitchingProtocols) | |
| 344 | 新增: } | |
| 345 | 新增:} | |
| @@ -0,0 +1,75 @@ | ||
| 1 | 新增:package relay | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/tls" | |
| 7 | 新增: "io" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "testing" | |
| 10 | 新增: "time" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/remotelink" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:// This exercises the real relay and peer transport together. It deliberately | |
| 16 | 新增:// does not claim device pairing, application RPC, or a mobile app is present. | |
| 17 | 新增:func TestMutualTLSAcrossRelay(t *testing.T) { | |
| 18 | 新增: service, server := testServer(t, Config{}) | |
| 19 | 新增: i := createRoom(t, server.URL, testAdmin, http.StatusCreated) | |
| 20 | 新增: hostWS := dial(t, server.URL, i, "host", i.HostToken, http.StatusSwitchingProtocols) | |
| 21 | 新增: clientWS := dial(t, server.URL, i, "client", i.ClientToken, http.StatusSwitchingProtocols) | |
| 22 | 新增: hostIdentity, err := remotelink.NewIdentity() | |
| 23 | 新增: if err != nil { | |
| 24 | 新增: t.Fatal(err) | |
| 25 | 新增: } | |
| 26 | 新增: clientIdentity, err := remotelink.NewIdentity() | |
| 27 | 新增: if err != nil { | |
| 28 | 新增: t.Fatal(err) | |
| 29 | 新增: } | |
| 30 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
| 31 | 新增: defer cancel() | |
| 32 | 新增: type result struct { | |
| 33 | 新增: connection *tls.Conn | |
| 34 | 新增: err error | |
| 35 | 新增: } | |
| 36 | 新增: hostResult := make(chan result, 1) | |
| 37 | 新增: go func() { | |
| 38 | 新增: connection, err := remotelink.Server(ctx, hostWS, hostIdentity, clientIdentity.Pin) | |
| 39 | 新增: hostResult <- result{connection, err} | |
| 40 | 新增: }() | |
| 41 | 新增: client, err := remotelink.Client(ctx, clientWS, clientIdentity, hostIdentity.Pin) | |
| 42 | 新增: if err != nil { | |
| 43 | 新增: t.Fatal(err) | |
| 44 | 新增: } | |
| 45 | 新增: host := <-hostResult | |
| 46 | 新增: if host.err != nil { | |
| 47 | 新增: t.Fatal(host.err) | |
| 48 | 新增: } | |
| 49 | 新增: defer host.connection.Close() | |
| 50 | 新增: defer client.Close() | |
| 51 | 新增: _ = host.connection.SetDeadline(time.Now().Add(3 * time.Second)) | |
| 52 | 新增: _ = client.SetDeadline(time.Now().Add(3 * time.Second)) | |
| 53 | 新增: payload := bytes.Repeat([]byte("Cage 远程传输 — binary\x00\xff\n"), 12000) | |
| 54 | 新增: writeDone := make(chan error, 1) | |
| 55 | 新增: go func() { _, err := client.Write(payload); writeDone <- err }() | |
| 56 | 新增: received := make([]byte, len(payload)) | |
| 57 | 新增: if _, err := io.ReadFull(host.connection, received); err != nil { | |
| 58 | 新增: t.Fatal(err) | |
| 59 | 新增: } | |
| 60 | 新增: if err := <-writeDone; err != nil || !bytes.Equal(received, payload) { | |
| 61 | 新增: t.Fatalf("large encrypted transfer failed: %v", err) | |
| 62 | 新增: } | |
| 63 | 新增: reply := []byte("主机已收到完整内容") | |
| 64 | 新增: go func() { _, err := host.connection.Write(reply); writeDone <- err }() | |
| 65 | 新增: if _, err := io.ReadFull(client, received[:len(reply)]); err != nil { | |
| 66 | 新增: t.Fatal(err) | |
| 67 | 新增: } | |
| 68 | 新增: if err := <-writeDone; err != nil || !bytes.Equal(received[:len(reply)], reply) { | |
| 69 | 新增: t.Fatalf("encrypted reply failed: %v", err) | |
| 70 | 新增: } | |
| 71 | 新增: _ = service.Close() | |
| 72 | 新增: if _, err := client.Read(received[:1]); err == nil { | |
| 73 | 新增: t.Fatal("relay shutdown did not close encrypted client stream") | |
| 74 | 新增: } | |
| 75 | 新增:} | |
| @@ -0,0 +1,229 @@ | ||
| 1 | 新增:// Package remotelink authenticates an already paired peer and carries TLS over | |
| 2 | 新增:// binary WebSocket messages. The relay is not trusted with plaintext or peer | |
| 3 | 新增:// identity. Pairing, persistent identity storage, and application integration | |
| 4 | 新增:// (including Claude Desktop) are outside this package. | |
| 5 | 新增:package remotelink | |
| 6 | 新增: | |
| 7 | 新增:import ( | |
| 8 | 新增: "context" | |
| 9 | 新增: "crypto" | |
| 10 | 新增: "crypto/ecdsa" | |
| 11 | 新增: "crypto/ed25519" | |
| 12 | 新增: "crypto/elliptic" | |
| 13 | 新增: "crypto/rand" | |
| 14 | 新增: "crypto/sha256" | |
| 15 | 新增: "crypto/subtle" | |
| 16 | 新增: "crypto/tls" | |
| 17 | 新增: "crypto/x509" | |
| 18 | 新增: "crypto/x509/pkix" | |
| 19 | 新增: "encoding/base64" | |
| 20 | 新增: "errors" | |
| 21 | 新增: "fmt" | |
| 22 | 新增: "math/big" | |
| 23 | 新增: "strings" | |
| 24 | 新增: "time" | |
| 25 | 新增: | |
| 26 | 新增: "github.com/gorilla/websocket" | |
| 27 | 新增:) | |
| 28 | 新增: | |
| 29 | 新增:const ( | |
| 30 | 新增: // Protocol is the required TLS application protocol. | |
| 31 | 新增: Protocol = "cage-remote/1" | |
| 32 | 新增: // MaxMessageSize limits each incoming WebSocket binary message, including | |
| 33 | 新增: // all its fragments. Outbound messages are at most 32 KiB. | |
| 34 | 新增: MaxMessageSize = 64 << 10 | |
| 35 | 新增: handshakeTimeout = 15 * time.Second | |
| 36 | 新增:) | |
| 37 | 新增: | |
| 38 | 新增:// Identity contains a TLS certificate and its public-key fingerprint. Pin uses | |
| 39 | 新增:// "sha256:" followed by standard, padded Base64 of SHA-256(SPKI DER). | |
| 40 | 新增:// Keep Certificate.PrivateKey private; exchange pins through the pairing flow. | |
| 41 | 新增:type Identity struct { | |
| 42 | 新增: Certificate tls.Certificate | |
| 43 | 新增: Pin string | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:// NewIdentity creates a temporary Ed25519 identity valid for 24 hours. It is | |
| 47 | 新增:// intended for transport validation, not production identity persistence. | |
| 48 | 新增:func NewIdentity() (*Identity, error) { | |
| 49 | 新增: _, private, err := ed25519.GenerateKey(rand.Reader) | |
| 50 | 新增: if err != nil { | |
| 51 | 新增: return nil, fmt.Errorf("generate identity key: %w", err) | |
| 52 | 新增: } | |
| 53 | 新增: return IdentityFromKey(private) | |
| 54 | 新增:} | |
| 55 | 新增: | |
| 56 | 新增:// IdentityFromKey issues a short-lived certificate for an existing device key. | |
| 57 | 新增:// The peer pin remains stable when this certificate is renewed. | |
| 58 | 新增:func IdentityFromKey(key ed25519.PrivateKey) (*Identity, error) { | |
| 59 | 新增: if len(key) != ed25519.PrivateKeySize { | |
| 60 | 新增: return nil, errors.New("invalid Ed25519 identity key") | |
| 61 | 新增: } | |
| 62 | 新增: return IdentityFromSigner(key) | |
| 63 | 新增:} | |
| 64 | 新增: | |
| 65 | 新增:// IdentityFromSigner also supports non-exportable P-256 device keys. TLS and | |
| 66 | 新增:// certificate issuance call Sign on the supplied signer; the private key need | |
| 67 | 新增:// not be readable by the application. | |
| 68 | 新增:func IdentityFromSigner(signer crypto.Signer) (*Identity, error) { | |
| 69 | 新增: if signer == nil { | |
| 70 | 新增: return nil, errors.New("device identity signer is required") | |
| 71 | 新增: } | |
| 72 | 新增: public := signer.Public() | |
| 73 | 新增: switch key := public.(type) { | |
| 74 | 新增: case ed25519.PublicKey: | |
| 75 | 新增: if len(key) != ed25519.PublicKeySize { | |
| 76 | 新增: return nil, errors.New("invalid Ed25519 identity public key") | |
| 77 | 新增: } | |
| 78 | 新增: case *ecdsa.PublicKey: | |
| 79 | 新增: if key == nil || key.Curve != elliptic.P256() { | |
| 80 | 新增: return nil, errors.New("device ECDSA signer must use P-256") | |
| 81 | 新增: } | |
| 82 | 新增: default: | |
| 83 | 新增: return nil, errors.New("device identity signer must use Ed25519 or P-256") | |
| 84 | 新增: } | |
| 85 | 新增: serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) | |
| 86 | 新增: if err != nil { | |
| 87 | 新增: return nil, fmt.Errorf("generate certificate serial: %w", err) | |
| 88 | 新增: } | |
| 89 | 新增: now := time.Now() | |
| 90 | 新增: template := &x509.Certificate{ | |
| 91 | 新增: SerialNumber: serial, | |
| 92 | 新增: Subject: pkix.Name{CommonName: "Cage temporary remote identity"}, | |
| 93 | 新增: NotBefore: now.Add(-time.Minute), NotAfter: now.Add(24 * time.Hour), | |
| 94 | 新增: KeyUsage: x509.KeyUsageDigitalSignature, | |
| 95 | 新增: ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, | |
| 96 | 新增: } | |
| 97 | 新增: der, err := x509.CreateCertificate(rand.Reader, template, template, public, signer) | |
| 98 | 新增: if err != nil { | |
| 99 | 新增: return nil, fmt.Errorf("create identity certificate: %w", err) | |
| 100 | 新增: } | |
| 101 | 新增: leaf, err := x509.ParseCertificate(der) | |
| 102 | 新增: if err != nil { | |
| 103 | 新增: return nil, fmt.Errorf("parse identity certificate: %w", err) | |
| 104 | 新增: } | |
| 105 | 新增: digest := sha256.Sum256(leaf.RawSubjectPublicKeyInfo) | |
| 106 | 新增: return &Identity{ | |
| 107 | 新增: Certificate: tls.Certificate{Certificate: [][]byte{der}, PrivateKey: signer, Leaf: leaf}, | |
| 108 | 新增: Pin: "sha256:" + base64.StdEncoding.EncodeToString(digest[:]), | |
| 109 | 新增: }, nil | |
| 110 | 新增:} | |
| 111 | 新增: | |
| 112 | 新增:// Client performs a mutually authenticated TLS 1.3 client handshake. expectedPin | |
| 113 | 新增:// must be the server identity established by pairing, never supplied by the | |
| 114 | 新增:// relay. Client takes exclusive ownership of ws and closes it on any failure. | |
| 115 | 新增:// ctx applies to the handshake only; a successful connection outlives ctx. | |
| 116 | 新增:func Client(ctx context.Context, ws *websocket.Conn, identity *Identity, expectedPin string) (*tls.Conn, error) { | |
| 117 | 新增: return handshake(ctx, ws, identity, expectedPin, false, false) | |
| 118 | 新增:} | |
| 119 | 新增: | |
| 120 | 新增:// Server is the server counterpart of Client. expectedPin must identify the | |
| 121 | 新增:// already paired client. It has the same ownership and context rules as Client. | |
| 122 | 新增:func Server(ctx context.Context, ws *websocket.Conn, identity *Identity, expectedPin string) (*tls.Conn, error) { | |
| 123 | 新增: return handshake(ctx, ws, identity, expectedPin, true, false) | |
| 124 | 新增:} | |
| 125 | 新增: | |
| 126 | 新增:// ServerAfterJoin allows up to two minutes for the other device to enter a | |
| 127 | 新增:// relay room. The normal handshake deadline starts when its first binary | |
| 128 | 新增:// message arrives. The caller owns the room invitation and its expiry. | |
| 129 | 新增:func ServerAfterJoin(ctx context.Context, ws *websocket.Conn, identity *Identity, expectedPin string) (*tls.Conn, error) { | |
| 130 | 新增: return handshake(ctx, ws, identity, expectedPin, true, true) | |
| 131 | 新增:} | |
| 132 | 新增: | |
| 133 | 新增:func peerVerifier(pin string) (func(tls.ConnectionState) error, error) { | |
| 134 | 新增: encoded, ok := strings.CutPrefix(pin, "sha256:") | |
| 135 | 新增: digest, err := base64.StdEncoding.DecodeString(encoded) | |
| 136 | 新增: if !ok || err != nil || len(digest) != sha256.Size || base64.StdEncoding.EncodeToString(digest) != encoded { | |
| 137 | 新增: return nil, errors.New("peer pin must be sha256: followed by padded Base64 of a SHA-256 SPKI digest") | |
| 138 | 新增: } | |
| 139 | 新增: return func(state tls.ConnectionState) error { | |
| 140 | 新增: if state.Version != tls.VersionTLS13 || state.NegotiatedProtocol != Protocol { | |
| 141 | 新增: return errors.New("peer did not negotiate the required TLS version and application protocol") | |
| 142 | 新增: } | |
| 143 | 新增: if len(state.PeerCertificates) == 0 { | |
| 144 | 新增: return errors.New("peer did not provide an identity certificate") | |
| 145 | 新增: } | |
| 146 | 新增: certificate := state.PeerCertificates[0] | |
| 147 | 新增: now := time.Now() | |
| 148 | 新增: if now.Before(certificate.NotBefore) || !now.Before(certificate.NotAfter) { | |
| 149 | 新增: return errors.New("peer identity certificate is outside its validity period") | |
| 150 | 新增: } | |
| 151 | 新增: actual := sha256.Sum256(certificate.RawSubjectPublicKeyInfo) | |
| 152 | 新增: if subtle.ConstantTimeCompare(actual[:], digest) != 1 { | |
| 153 | 新增: return errors.New("peer identity does not match the paired public key") | |
| 154 | 新增: } | |
| 155 | 新增: return nil | |
| 156 | 新增: }, nil | |
| 157 | 新增:} | |
| 158 | 新增: | |
| 159 | 新增:func handshake(ctx context.Context, ws *websocket.Conn, identity *Identity, expectedPin string, server, waitForJoin bool) (_ *tls.Conn, err error) { | |
| 160 | 新增: if ws == nil { | |
| 161 | 新增: return nil, errors.New("WebSocket connection is required") | |
| 162 | 新增: } | |
| 163 | 新增: defer func() { | |
| 164 | 新增: if err != nil { | |
| 165 | 新增: _ = ws.Close() | |
| 166 | 新增: } | |
| 167 | 新增: }() | |
| 168 | 新增: verify, err := peerVerifier(expectedPin) | |
| 169 | 新增: if err != nil { | |
| 170 | 新增: return nil, err | |
| 171 | 新增: } | |
| 172 | 新增: if identity == nil || len(identity.Certificate.Certificate) == 0 || identity.Certificate.PrivateKey == nil { | |
| 173 | 新增: return nil, errors.New("local identity certificate and private key are required") | |
| 174 | 新增: } | |
| 175 | 新增: config := &tls.Config{ | |
| 176 | 新增: MinVersion: tls.VersionTLS13, MaxVersion: tls.VersionTLS13, | |
| 177 | 新增: NextProtos: []string{Protocol}, | |
| 178 | 新增: Certificates: []tls.Certificate{identity.Certificate}, | |
| 179 | 新增: VerifyConnection: verify, | |
| 180 | 新增: SessionTicketsDisabled: true, | |
| 181 | 新增: } | |
| 182 | 新增: stream := newWebSocketConn(ws) | |
| 183 | 新增: if waitForJoin { | |
| 184 | 新增: wait, cancel := context.WithTimeout(ctx, 2*time.Minute) | |
| 185 | 新增: stop := context.AfterFunc(wait, func() { _ = stream.Close() }) | |
| 186 | 新增: kind, first, readErr := ws.NextReader() | |
| 187 | 新增: stop() | |
| 188 | 新增: waitErr := wait.Err() | |
| 189 | 新增: cancel() | |
| 190 | 新增: if waitErr != nil { | |
| 191 | 新增: return nil, fmt.Errorf("waiting for paired device: %w", waitErr) | |
| 192 | 新增: } | |
| 193 | 新增: if readErr != nil || kind != websocket.BinaryMessage { | |
| 194 | 新增: return nil, errors.New("peer did not send a binary TLS handshake") | |
| 195 | 新增: } | |
| 196 | 新增: // NextReader has consumed the message header only. The first TLS record | |
| 197 | 新增: // remains in the bounded WebSocket reader used by webSocketConn.Read. | |
| 198 | 新增: stream.reader = first | |
| 199 | 新增: } | |
| 200 | 新增: var connection *tls.Conn | |
| 201 | 新增: if server { | |
| 202 | 新增: config.ClientAuth = tls.RequireAnyClientCert | |
| 203 | 新增: connection = tls.Server(stream, config) | |
| 204 | 新增: } else { | |
| 205 | 新增: // Paired public keys replace Web PKI trust. VerifyConnection is mandatory | |
| 206 | 新增: // and checks the exact key, certificate validity, TLS version, and ALPN. | |
| 207 | 新增: config.InsecureSkipVerify = true | |
| 208 | 新增: connection = tls.Client(stream, config) | |
| 209 | 新增: } | |
| 210 | 新增: ctx, cancel := context.WithTimeout(ctx, handshakeTimeout) | |
| 211 | 新增: defer cancel() | |
| 212 | 新增: deadline, _ := ctx.Deadline() | |
| 213 | 新增: if err := stream.SetDeadline(deadline); err != nil { | |
| 214 | 新增: return nil, fmt.Errorf("set handshake deadline: %w", err) | |
| 215 | 新增: } | |
| 216 | 新增: stop := context.AfterFunc(ctx, func() { _ = stream.Close() }) | |
| 217 | 新增: err = connection.HandshakeContext(ctx) | |
| 218 | 新增: stop() | |
| 219 | 新增: if ctx.Err() != nil { | |
| 220 | 新增: return nil, fmt.Errorf("remote TLS handshake: %w", ctx.Err()) | |
| 221 | 新增: } | |
| 222 | 新增: if err != nil { | |
| 223 | 新增: return nil, fmt.Errorf("remote TLS handshake: %w", err) | |
| 224 | 新增: } | |
| 225 | 新增: if err := stream.SetDeadline(time.Time{}); err != nil { | |
| 226 | 新增: return nil, fmt.Errorf("clear handshake deadline: %w", err) | |
| 227 | 新增: } | |
| 228 | 新增: return connection, nil | |
| 229 | 新增:} | |
| @@ -0,0 +1,315 @@ | ||
| 1 | 新增:package remotelink | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/ed25519" | |
| 7 | 新增: "crypto/rand" | |
| 8 | 新增: "crypto/sha256" | |
| 9 | 新增: "crypto/tls" | |
| 10 | 新增: "crypto/x509" | |
| 11 | 新增: "encoding/base64" | |
| 12 | 新增: "errors" | |
| 13 | 新增: "io" | |
| 14 | 新增: "math/big" | |
| 15 | 新增: "net/http" | |
| 16 | 新增: "net/http/httptest" | |
| 17 | 新增: "strings" | |
| 18 | 新增: "testing" | |
| 19 | 新增: "time" | |
| 20 | 新增: | |
| 21 | 新增: "github.com/gorilla/websocket" | |
| 22 | 新增:) | |
| 23 | 新增: | |
| 24 | 新增:type handshakeResult struct { | |
| 25 | 新增: connection *tls.Conn | |
| 26 | 新增: err error | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:func identityForTest(t *testing.T) *Identity { | |
| 30 | 新增: t.Helper() | |
| 31 | 新增: identity, err := NewIdentity() | |
| 32 | 新增: if err != nil { | |
| 33 | 新增: t.Fatal(err) | |
| 34 | 新增: } | |
| 35 | 新增: return identity | |
| 36 | 新增:} | |
| 37 | 新增: | |
| 38 | 新增:func socketsForTest(t *testing.T) (*websocket.Conn, *websocket.Conn) { | |
| 39 | 新增: t.Helper() | |
| 40 | 新增: accepted := make(chan *websocket.Conn, 1) | |
| 41 | 新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 42 | 新增: ws, err := (&websocket.Upgrader{}).Upgrade(w, r, nil) | |
| 43 | 新增: if err != nil { | |
| 44 | 新增: t.Errorf("upgrade: %v", err) | |
| 45 | 新增: return | |
| 46 | 新增: } | |
| 47 | 新增: accepted <- ws | |
| 48 | 新增: })) | |
| 49 | 新增: t.Cleanup(server.Close) | |
| 50 | 新增: client, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http"), nil) | |
| 51 | 新增: if err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: peer := <-accepted | |
| 55 | 新增: t.Cleanup(func() { _ = client.Close(); _ = peer.Close() }) | |
| 56 | 新增: return client, peer | |
| 57 | 新增:} | |
| 58 | 新增: | |
| 59 | 新增:func connectForTest(t *testing.T, ctx context.Context) (*tls.Conn, *tls.Conn, *websocket.Conn) { | |
| 60 | 新增: t.Helper() | |
| 61 | 新增: clientIdentity, serverIdentity := identityForTest(t), identityForTest(t) | |
| 62 | 新增: clientWS, serverWS := socketsForTest(t) | |
| 63 | 新增: result := make(chan handshakeResult, 1) | |
| 64 | 新增: go func() { | |
| 65 | 新增: connection, err := Server(ctx, serverWS, serverIdentity, clientIdentity.Pin) | |
| 66 | 新增: result <- handshakeResult{connection, err} | |
| 67 | 新增: }() | |
| 68 | 新增: client, err := Client(ctx, clientWS, clientIdentity, serverIdentity.Pin) | |
| 69 | 新增: if err != nil { | |
| 70 | 新增: t.Fatal(err) | |
| 71 | 新增: } | |
| 72 | 新增: remote := <-result | |
| 73 | 新增: if remote.err != nil { | |
| 74 | 新增: t.Fatal(remote.err) | |
| 75 | 新增: } | |
| 76 | 新增: return client, remote.connection, serverWS | |
| 77 | 新增:} | |
| 78 | 新增: | |
| 79 | 新增:func TestMutualTLSAndBidirectionalStream(t *testing.T) { | |
| 80 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
| 81 | 新增: defer cancel() | |
| 82 | 新增: client, server, _ := connectForTest(t, ctx) | |
| 83 | 新增: for _, connection := range []*tls.Conn{client, server} { | |
| 84 | 新增: state := connection.ConnectionState() | |
| 85 | 新增: if state.Version != tls.VersionTLS13 || state.NegotiatedProtocol != Protocol || len(state.PeerCertificates) != 1 { | |
| 86 | 新增: t.Fatalf("unexpected authenticated connection: version=%x protocol=%q peers=%d", state.Version, state.NegotiatedProtocol, len(state.PeerCertificates)) | |
| 87 | 新增: } | |
| 88 | 新增: transport := connection.NetConn().(*webSocketConn) | |
| 89 | 新增: if !transport.writeDeadline.IsZero() { | |
| 90 | 新增: t.Fatal("handshake write deadline was not cleared") | |
| 91 | 新增: } | |
| 92 | 新增: if err := connection.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { | |
| 93 | 新增: t.Fatal(err) | |
| 94 | 新增: } | |
| 95 | 新增: } | |
| 96 | 新增: // A completed connection must survive cancellation of its handshake context. | |
| 97 | 新增: cancel() | |
| 98 | 新增: payload := make([]byte, 256<<10) | |
| 99 | 新增: if _, err := rand.Read(payload); err != nil { | |
| 100 | 新增: t.Fatal(err) | |
| 101 | 新增: } | |
| 102 | 新增: reply := []byte("手机已连接,回复不依赖 WebSocket 消息边界。") | |
| 103 | 新增: done := make(chan error, 1) | |
| 104 | 新增: go func() { | |
| 105 | 新增: received := make([]byte, len(payload)) | |
| 106 | 新增: if _, err := io.ReadFull(server, received); err != nil { | |
| 107 | 新增: done <- err | |
| 108 | 新增: return | |
| 109 | 新增: } | |
| 110 | 新增: if !bytes.Equal(payload, received) { | |
| 111 | 新增: done <- errors.New("server received altered plaintext") | |
| 112 | 新增: return | |
| 113 | 新增: } | |
| 114 | 新增: _, err := server.Write(reply) | |
| 115 | 新增: done <- err | |
| 116 | 新增: }() | |
| 117 | 新增: if _, err := client.Write(payload); err != nil { | |
| 118 | 新增: t.Fatal(err) | |
| 119 | 新增: } | |
| 120 | 新增: received := make([]byte, len(reply)) | |
| 121 | 新增: if _, err := io.ReadFull(client, received); err != nil || !bytes.Equal(received, reply) { | |
| 122 | 新增: t.Fatalf("client reply: %q, %v", received, err) | |
| 123 | 新增: } | |
| 124 | 新增: if err := <-done; err != nil { | |
| 125 | 新增: t.Fatal(err) | |
| 126 | 新增: } | |
| 127 | 新增:} | |
| 128 | 新增: | |
| 129 | 新增:func TestRejectWrongPeerPins(t *testing.T) { | |
| 130 | 新增: for _, side := range []string{"client", "server"} { | |
| 131 | 新增: t.Run(side, func(t *testing.T) { | |
| 132 | 新增: clientIdentity, serverIdentity, impostor := identityForTest(t), identityForTest(t), identityForTest(t) | |
| 133 | 新增: clientWS, serverWS := socketsForTest(t) | |
| 134 | 新增: clientPin, serverPin := clientIdentity.Pin, serverIdentity.Pin | |
| 135 | 新增: if side == "client" { | |
| 136 | 新增: serverPin = impostor.Pin | |
| 137 | 新增: } else { | |
| 138 | 新增: clientPin = impostor.Pin | |
| 139 | 新增: } | |
| 140 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
| 141 | 新增: defer cancel() | |
| 142 | 新增: result := make(chan error, 1) | |
| 143 | 新增: go func() { _, err := Server(ctx, serverWS, serverIdentity, clientPin); result <- err }() | |
| 144 | 新增: client, clientErr := Client(ctx, clientWS, clientIdentity, serverPin) | |
| 145 | 新增: serverErr := <-result | |
| 146 | 新增: if side == "client" && (clientErr == nil || !strings.Contains(clientErr.Error(), "paired public key")) { | |
| 147 | 新增: t.Fatalf("client accepted wrong server pin: %v", clientErr) | |
| 148 | 新增: } | |
| 149 | 新增: if side == "server" && (serverErr == nil || !strings.Contains(serverErr.Error(), "paired public key")) { | |
| 150 | 新增: t.Fatalf("server accepted wrong client pin: %v", serverErr) | |
| 151 | 新增: } | |
| 152 | 新增: if client != nil { | |
| 153 | 新增: _ = client.NetConn().Close() | |
| 154 | 新增: } | |
| 155 | 新增: }) | |
| 156 | 新增: } | |
| 157 | 新增:} | |
| 158 | 新增: | |
| 159 | 新增:func TestRejectEmptyOrMalformedPins(t *testing.T) { | |
| 160 | 新增: identity := identityForTest(t) | |
| 161 | 新增: for _, connect := range []struct { | |
| 162 | 新增: name string | |
| 163 | 新增: fn func(context.Context, *websocket.Conn, *Identity, string) (*tls.Conn, error) | |
| 164 | 新增: }{{"client", Client}, {"server", Server}} { | |
| 165 | 新增: for _, pin := range []string{"", "sha256:", "sha256:not-base64", strings.TrimSuffix(identity.Pin, "=")} { | |
| 166 | 新增: t.Run(connect.name+"/"+pin, func(t *testing.T) { | |
| 167 | 新增: ws, _ := socketsForTest(t) | |
| 168 | 新增: if _, err := connect.fn(context.Background(), ws, identity, pin); err == nil { | |
| 169 | 新增: t.Fatal("accepted missing or malformed pin") | |
| 170 | 新增: } | |
| 171 | 新增: }) | |
| 172 | 新增: } | |
| 173 | 新增: } | |
| 174 | 新增:} | |
| 175 | 新增: | |
| 176 | 新增:func TestRejectExpiredPinnedCertificate(t *testing.T) { | |
| 177 | 新增: clientIdentity, serverIdentity := identityForTest(t), identityForTest(t) | |
| 178 | 新增: private := serverIdentity.Certificate.PrivateKey.(ed25519.PrivateKey) | |
| 179 | 新增: template := &x509.Certificate{SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-2 * time.Hour), NotAfter: time.Now().Add(-time.Hour), KeyUsage: x509.KeyUsageDigitalSignature} | |
| 180 | 新增: der, err := x509.CreateCertificate(rand.Reader, template, template, private.Public(), private) | |
| 181 | 新增: if err != nil { | |
| 182 | 新增: t.Fatal(err) | |
| 183 | 新增: } | |
| 184 | 新增: leaf, err := x509.ParseCertificate(der) | |
| 185 | 新增: if err != nil { | |
| 186 | 新增: t.Fatal(err) | |
| 187 | 新增: } | |
| 188 | 新增: serverIdentity.Certificate.Certificate = [][]byte{der} | |
| 189 | 新增: serverIdentity.Certificate.Leaf = leaf | |
| 190 | 新增: digest := sha256.Sum256(leaf.RawSubjectPublicKeyInfo) | |
| 191 | 新增: if serverIdentity.Pin != "sha256:"+base64.StdEncoding.EncodeToString(digest[:]) { | |
| 192 | 新增: t.Fatal("test changed the pinned public key") | |
| 193 | 新增: } | |
| 194 | 新增: clientWS, serverWS := socketsForTest(t) | |
| 195 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
| 196 | 新增: defer cancel() | |
| 197 | 新增: result := make(chan error, 1) | |
| 198 | 新增: go func() { _, err := Server(ctx, serverWS, serverIdentity, clientIdentity.Pin); result <- err }() | |
| 199 | 新增: _, err = Client(ctx, clientWS, clientIdentity, serverIdentity.Pin) | |
| 200 | 新增: if err == nil || !strings.Contains(err.Error(), "validity period") { | |
| 201 | 新增: t.Fatalf("expired pinned certificate accepted: %v", err) | |
| 202 | 新增: } | |
| 203 | 新增: <-result | |
| 204 | 新增:} | |
| 205 | 新增: | |
| 206 | 新增:func TestRejectTamperedTLSRecord(t *testing.T) { | |
| 207 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
| 208 | 新增: defer cancel() | |
| 209 | 新增: client, _, serverWS := connectForTest(t, ctx) | |
| 210 | 新增: if err := client.SetReadDeadline(time.Now().Add(2 * time.Second)); err != nil { | |
| 211 | 新增: t.Fatal(err) | |
| 212 | 新增: } | |
| 213 | 新增: // An untrusted forwarding relay can inject a binary frame but cannot create | |
| 214 | 新增: // a TLS record with a valid authentication tag after the handshake. | |
| 215 | 新增: forged := append([]byte{23, 3, 3, 0, 17}, make([]byte, 17)...) | |
| 216 | 新增: if err := serverWS.WriteMessage(websocket.BinaryMessage, forged); err != nil { | |
| 217 | 新增: t.Fatal(err) | |
| 218 | 新增: } | |
| 219 | 新增: var output [1]byte | |
| 220 | 新增: if n, err := client.Read(output[:]); n != 0 || err == nil || !strings.Contains(err.Error(), "bad record MAC") { | |
| 221 | 新增: t.Fatalf("tampering result: bytes=%d error=%v", n, err) | |
| 222 | 新增: } | |
| 223 | 新增:} | |
| 224 | 新增: | |
| 225 | 新增:func TestCancelHandshake(t *testing.T) { | |
| 226 | 新增: clientIdentity, serverIdentity := identityForTest(t), identityForTest(t) | |
| 227 | 新增: clientWS, silentPeer := socketsForTest(t) | |
| 228 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 229 | 新增: defer cancel() | |
| 230 | 新增: result := make(chan error, 1) | |
| 231 | 新增: go func() { _, err := Client(ctx, clientWS, clientIdentity, serverIdentity.Pin); result <- err }() | |
| 232 | 新增: if err := silentPeer.SetReadDeadline(time.Now().Add(2 * time.Second)); err != nil { | |
| 233 | 新增: t.Fatal(err) | |
| 234 | 新增: } | |
| 235 | 新增: if _, _, err := silentPeer.ReadMessage(); err != nil { | |
| 236 | 新增: t.Fatal(err) | |
| 237 | 新增: } | |
| 238 | 新增: cancel() | |
| 239 | 新增: select { | |
| 240 | 新增: case err := <-result: | |
| 241 | 新增: if !errors.Is(err, context.Canceled) { | |
| 242 | 新增: t.Fatalf("canceled handshake: %v", err) | |
| 243 | 新增: } | |
| 244 | 新增: case <-time.After(2 * time.Second): | |
| 245 | 新增: t.Fatal("cancellation did not unblock handshake") | |
| 246 | 新增: } | |
| 247 | 新增:} | |
| 248 | 新增: | |
| 249 | 新增:func TestRejectTextAndOversizedMessages(t *testing.T) { | |
| 250 | 新增: for _, test := range []struct { | |
| 251 | 新增: name string | |
| 252 | 新增: kind int | |
| 253 | 新增: data []byte | |
| 254 | 新增: }{ | |
| 255 | 新增: {"text", websocket.TextMessage, []byte("not a binary transport")}, | |
| 256 | 新增: {"oversized", websocket.BinaryMessage, make([]byte, MaxMessageSize+1)}, | |
| 257 | 新增: } { | |
| 258 | 新增: t.Run(test.name, func(t *testing.T) { | |
| 259 | 新增: local, peer := socketsForTest(t) | |
| 260 | 新增: stream := newWebSocketConn(local) | |
| 261 | 新增: _ = stream.SetReadDeadline(time.Now().Add(2 * time.Second)) | |
| 262 | 新增: done := make(chan error, 1) | |
| 263 | 新增: go func() { done <- peer.WriteMessage(test.kind, test.data) }() | |
| 264 | 新增: _, err := io.Copy(io.Discard, stream) | |
| 265 | 新增: if err == nil { | |
| 266 | 新增: t.Fatal("accepted invalid WebSocket message") | |
| 267 | 新增: } | |
| 268 | 新增: if test.name == "text" && !strings.Contains(err.Error(), "only binary") { | |
| 269 | 新增: t.Fatalf("wrong text rejection: %v", err) | |
| 270 | 新增: } | |
| 271 | 新增: if test.name == "oversized" && !errors.Is(err, websocket.ErrReadLimit) { | |
| 272 | 新增: t.Fatalf("wrong size rejection: %v", err) | |
| 273 | 新增: } | |
| 274 | 新增: <-done | |
| 275 | 新增: }) | |
| 276 | 新增: } | |
| 277 | 新增:} | |
| 278 | 新增: | |
| 279 | 新增:func TestWriteFragmentsAndReadAcrossBoundaries(t *testing.T) { | |
| 280 | 新增: local, peer := socketsForTest(t) | |
| 281 | 新增: stream := newWebSocketConn(local) | |
| 282 | 新增: payload := bytes.Repeat([]byte("binary-stream-"), 8000) | |
| 283 | 新增: done := make(chan error, 1) | |
| 284 | 新增: go func() { _, err := stream.Write(payload); done <- err }() | |
| 285 | 新增: var received []byte | |
| 286 | 新增: for len(received) < len(payload) { | |
| 287 | 新增: kind, message, err := peer.ReadMessage() | |
| 288 | 新增: if err != nil { | |
| 289 | 新增: t.Fatal(err) | |
| 290 | 新增: } | |
| 291 | 新增: if kind != websocket.BinaryMessage || len(message) > writeMessageSize { | |
| 292 | 新增: t.Fatalf("invalid write frame: type=%d size=%d", kind, len(message)) | |
| 293 | 新增: } | |
| 294 | 新增: received = append(received, message...) | |
| 295 | 新增: } | |
| 296 | 新增: if err := <-done; err != nil || !bytes.Equal(received, payload) { | |
| 297 | 新增: t.Fatalf("fragmented write changed bytes: %v", err) | |
| 298 | 新增: } | |
| 299 | 新增: go func() { | |
| 300 | 新增: for _, part := range [][]byte{nil, []byte("ab"), []byte("c"), []byte("def")} { | |
| 301 | 新增: if err := peer.WriteMessage(websocket.BinaryMessage, part); err != nil { | |
| 302 | 新增: done <- err | |
| 303 | 新增: return | |
| 304 | 新增: } | |
| 305 | 新增: } | |
| 306 | 新增: done <- nil | |
| 307 | 新增: }() | |
| 308 | 新增: var joined [6]byte | |
| 309 | 新增: if _, err := io.ReadFull(stream, joined[:]); err != nil || string(joined[:]) != "abcdef" { | |
| 310 | 新增: t.Fatalf("message boundaries leaked into stream: %q %v", joined, err) | |
| 311 | 新增: } | |
| 312 | 新增: if err := <-done; err != nil { | |
| 313 | 新增: t.Fatal(err) | |
| 314 | 新增: } | |
| 315 | 新增:} | |
| @@ -0,0 +1,153 @@ | ||
| 1 | 新增:package remotelink | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "io" | |
| 6 | 新增: "net" | |
| 7 | 新增: "os" | |
| 8 | 新增: "sync" | |
| 9 | 新增: "time" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/gorilla/websocket" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:const writeMessageSize = 32 << 10 | |
| 15 | 新增: | |
| 16 | 新增:// webSocketConn treats binary messages as one byte stream. After an I/O timeout | |
| 17 | 新增:// the WebSocket must be replaced, as required by gorilla/websocket. In | |
| 18 | 新增:// particular a write deadline closes the socket to interrupt a blocked write; | |
| 19 | 新增:// this avoids concurrently changing gorilla's writer-owned deadline field. | |
| 20 | 新增:type webSocketConn struct { | |
| 21 | 新增: ws *websocket.Conn | |
| 22 | 新增: readMu, writeMu sync.Mutex | |
| 23 | 新增: reader io.Reader | |
| 24 | 新增: closeOnce sync.Once | |
| 25 | 新增: closeErr error | |
| 26 | 新增: deadlineMu sync.Mutex | |
| 27 | 新增: writeDeadline time.Time | |
| 28 | 新增: writeTimer *time.Timer | |
| 29 | 新增: writeGeneration uint64 | |
| 30 | 新增: writeActive, writeExpired bool | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:var _ net.Conn = (*webSocketConn)(nil) | |
| 34 | 新增: | |
| 35 | 新增:func newWebSocketConn(ws *websocket.Conn) *webSocketConn { | |
| 36 | 新增: ws.SetReadLimit(MaxMessageSize) | |
| 37 | 新增: _ = ws.SetWriteDeadline(time.Time{}) | |
| 38 | 新增: return &webSocketConn{ws: ws} | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:func (c *webSocketConn) Read(p []byte) (int, error) { | |
| 42 | 新增: if len(p) == 0 { | |
| 43 | 新增: return 0, nil | |
| 44 | 新增: } | |
| 45 | 新增: c.readMu.Lock() | |
| 46 | 新增: defer c.readMu.Unlock() | |
| 47 | 新增: for { | |
| 48 | 新增: if c.reader == nil { | |
| 49 | 新增: kind, reader, err := c.ws.NextReader() | |
| 50 | 新增: if err != nil { | |
| 51 | 新增: return 0, err | |
| 52 | 新增: } | |
| 53 | 新增: if kind != websocket.BinaryMessage { | |
| 54 | 新增: _ = c.Close() | |
| 55 | 新增: return 0, errors.New("remote transport accepts only binary WebSocket messages") | |
| 56 | 新增: } | |
| 57 | 新增: c.reader = reader | |
| 58 | 新增: } | |
| 59 | 新增: n, err := c.reader.Read(p) | |
| 60 | 新增: if err == io.EOF { | |
| 61 | 新增: c.reader = nil | |
| 62 | 新增: if n == 0 { | |
| 63 | 新增: continue | |
| 64 | 新增: } | |
| 65 | 新增: err = nil | |
| 66 | 新增: } | |
| 67 | 新增: return n, err | |
| 68 | 新增: } | |
| 69 | 新增:} | |
| 70 | 新增: | |
| 71 | 新增:func (c *webSocketConn) Write(p []byte) (int, error) { | |
| 72 | 新增: c.writeMu.Lock() | |
| 73 | 新增: defer c.writeMu.Unlock() | |
| 74 | 新增: c.deadlineMu.Lock() | |
| 75 | 新增: if !c.writeDeadline.IsZero() && !time.Now().Before(c.writeDeadline) { | |
| 76 | 新增: c.deadlineMu.Unlock() | |
| 77 | 新增: return 0, os.ErrDeadlineExceeded | |
| 78 | 新增: } | |
| 79 | 新增: c.writeActive, c.writeExpired = true, false | |
| 80 | 新增: c.scheduleWriteDeadline() | |
| 81 | 新增: c.deadlineMu.Unlock() | |
| 82 | 新增: n, err := 0, error(nil) | |
| 83 | 新增: for n < len(p) { | |
| 84 | 新增: end := min(n+writeMessageSize, len(p)) | |
| 85 | 新增: if err = c.ws.WriteMessage(websocket.BinaryMessage, p[n:end]); err != nil { | |
| 86 | 新增: break | |
| 87 | 新增: } | |
| 88 | 新增: n = end | |
| 89 | 新增: } | |
| 90 | 新增: c.deadlineMu.Lock() | |
| 91 | 新增: c.writeActive = false | |
| 92 | 新增: c.writeGeneration++ | |
| 93 | 新增: if c.writeTimer != nil { | |
| 94 | 新增: c.writeTimer.Stop() | |
| 95 | 新增: c.writeTimer = nil | |
| 96 | 新增: } | |
| 97 | 新增: if c.writeExpired { | |
| 98 | 新增: err = os.ErrDeadlineExceeded | |
| 99 | 新增: } | |
| 100 | 新增: c.deadlineMu.Unlock() | |
| 101 | 新增: return n, err | |
| 102 | 新增:} | |
| 103 | 新增: | |
| 104 | 新增:func (c *webSocketConn) Close() error { | |
| 105 | 新增: c.closeOnce.Do(func() { c.closeErr = c.ws.Close() }) | |
| 106 | 新增: return c.closeErr | |
| 107 | 新增:} | |
| 108 | 新增: | |
| 109 | 新增:func (c *webSocketConn) LocalAddr() net.Addr { return c.ws.UnderlyingConn().LocalAddr() } | |
| 110 | 新增:func (c *webSocketConn) RemoteAddr() net.Addr { return c.ws.UnderlyingConn().RemoteAddr() } | |
| 111 | 新增: | |
| 112 | 新增:func (c *webSocketConn) SetDeadline(deadline time.Time) error { | |
| 113 | 新增: if err := c.SetReadDeadline(deadline); err != nil { | |
| 114 | 新增: return err | |
| 115 | 新增: } | |
| 116 | 新增: return c.SetWriteDeadline(deadline) | |
| 117 | 新增:} | |
| 118 | 新增: | |
| 119 | 新增:func (c *webSocketConn) SetReadDeadline(deadline time.Time) error { | |
| 120 | 新增: return c.ws.UnderlyingConn().SetReadDeadline(deadline) | |
| 121 | 新增:} | |
| 122 | 新增: | |
| 123 | 新增:func (c *webSocketConn) SetWriteDeadline(deadline time.Time) error { | |
| 124 | 新增: c.deadlineMu.Lock() | |
| 125 | 新增: defer c.deadlineMu.Unlock() | |
| 126 | 新增: c.writeDeadline = deadline | |
| 127 | 新增: c.scheduleWriteDeadline() | |
| 128 | 新增: return nil | |
| 129 | 新增:} | |
| 130 | 新增: | |
| 131 | 新增:// scheduleWriteDeadline is called with deadlineMu held. Each generation fences | |
| 132 | 新增:// a timer canceled by a successful write or a changed deadline. | |
| 133 | 新增:func (c *webSocketConn) scheduleWriteDeadline() { | |
| 134 | 新增: c.writeGeneration++ | |
| 135 | 新增: if c.writeTimer != nil { | |
| 136 | 新增: c.writeTimer.Stop() | |
| 137 | 新增: c.writeTimer = nil | |
| 138 | 新增: } | |
| 139 | 新增: if !c.writeActive || c.writeDeadline.IsZero() { | |
| 140 | 新增: return | |
| 141 | 新增: } | |
| 142 | 新增: generation := c.writeGeneration | |
| 143 | 新增: c.writeTimer = time.AfterFunc(time.Until(c.writeDeadline), func() { | |
| 144 | 新增: c.deadlineMu.Lock() | |
| 145 | 新增: if !c.writeActive || c.writeGeneration != generation { | |
| 146 | 新增: c.deadlineMu.Unlock() | |
| 147 | 新增: return | |
| 148 | 新增: } | |
| 149 | 新增: c.writeExpired = true | |
| 150 | 新增: c.deadlineMu.Unlock() | |
| 151 | 新增: _ = c.Close() | |
| 152 | 新增: }) | |
| 153 | 新增:} | |

