| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/ed25519" |
| 6 | "crypto/rand" |
| 7 | "encoding/base64" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "net/http" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | "time" |
| 16 | "unicode" |
| 17 | "unicode/utf8" |
| 18 | |
| 19 | qrcode "github.com/skip2/go-qrcode" |
| 20 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 21 | "github.com/sylvinus/agent-vm/internal/keepawake" |
| 22 | "github.com/sylvinus/agent-vm/internal/mobilelink" |
| 23 | "github.com/sylvinus/agent-vm/internal/remotelink" |
| 24 | ) |
| 25 | |
| 26 | |
| 27 | type phoneRecord struct { |
| 28 | Seed []byte |
| 29 | Pin, Relay, Lookup, Admin string |
| 30 | Device *mobilelink.DeviceInfo `json:"device,omitempty"` |
| 31 | } |
| 32 | type mobilePairing struct { |
| 33 | mu sync.Mutex |
| 34 | browser, desktop phoneSurfaceState |
| 35 | roomProof string |
| 36 | roomCtx context.Context |
| 37 | pending context.CancelFunc |
| 38 | serving context.CancelFunc |
| 39 | record *phoneRecord |
| 40 | status string |
| 41 | closed bool |
| 42 | powerCtx context.Context |
| 43 | powerDone <-chan struct{} |
| 44 | power keepawake.State |
| 45 | } |
| 46 | |
| 47 | func (s *Server) phoneFile() string { return filepath.Join(s.profile, "mobile-paired-device.json") } |
| 48 | |
| 49 | |
| 50 | |
| 51 | func (s *Server) nativePhoneRoom(r *http.Request) context.Context { |
| 52 | if r.URL.Path != "/api/mobile/device" && !strings.HasPrefix(r.URL.Path, "/api/mobile/cli/") && !strings.HasPrefix(r.URL.Path, "/api/mobile/browser/") && !strings.HasPrefix(r.URL.Path, "/api/mobile/desktop/") { |
| 53 | return nil |
| 54 | } |
| 55 | s.phones.mu.Lock() |
| 56 | defer s.phones.mu.Unlock() |
| 57 | if s.phones.closed || s.phones.record == nil || !s.phones.pairedRequestLocked(r) { |
| 58 | return nil |
| 59 | } |
| 60 | return s.phones.roomCtx |
| 61 | } |
| 62 | |
| 63 | func (s *Server) restorePhone() error { |
| 64 | b, err := os.ReadFile(s.phoneFile()) |
| 65 | if os.IsNotExist(err) { |
| 66 | return nil |
| 67 | } |
| 68 | if err != nil { |
| 69 | return err |
| 70 | } |
| 71 | var r phoneRecord |
| 72 | if json.Unmarshal(b, &r) != nil || len(r.Seed) != ed25519.SeedSize || !mobilelink.ValidRelayOrigin(r.Relay) { |
| 73 | return errors.New("无法读取手机配对记录") |
| 74 | } |
| 75 | s.phones.mu.Lock() |
| 76 | defer s.phones.mu.Unlock() |
| 77 | s.attachPhone(r) |
| 78 | return nil |
| 79 | } |
| 80 | func (s *Server) attachPhone(r phoneRecord) { |
| 81 | ctx, cancel := context.WithCancel(context.Background()) |
| 82 | s.phones.serving = cancel |
| 83 | s.phones.record = &r |
| 84 | s.phones.powerCtx = ctx |
| 85 | done := make(chan struct{}) |
| 86 | s.phones.powerDone = done |
| 87 | go func() { |
| 88 | defer close(done) |
| 89 | keepawake.Run(ctx, func(state keepawake.State) { |
| 90 | s.phones.mu.Lock() |
| 91 | if s.phones.powerCtx == ctx { |
| 92 | s.phones.power = state |
| 93 | } |
| 94 | s.phones.mu.Unlock() |
| 95 | if state.Error != "" { |
| 96 | diagnostics.Log("warn", "mobile-remote", "keep-awake request failed: "+state.Error) |
| 97 | } |
| 98 | }) |
| 99 | }() |
| 100 | go func() { |
| 101 | delay := time.Second |
| 102 | for ctx.Err() == nil { |
| 103 | start := time.Now() |
| 104 | err := s.phoneRoom(ctx, r) |
| 105 | if ctx.Err() != nil { |
| 106 | return |
| 107 | } |
| 108 | if err == nil || time.Since(start) > time.Minute { |
| 109 | delay = time.Second |
| 110 | } else { |
| 111 | delay = min(30*time.Second, 2*delay) |
| 112 | } |
| 113 | select { |
| 114 | case <-ctx.Done(): |
| 115 | return |
| 116 | case <-time.After(delay): |
| 117 | } |
| 118 | } |
| 119 | }() |
| 120 | } |
| 121 | func (s *Server) phoneRoom(ctx context.Context, r phoneRecord) error { |
| 122 | id, err := remotelink.IdentityFromKey(ed25519.NewKeyFromSeed(r.Seed)) |
| 123 | if err != nil { |
| 124 | return err |
| 125 | } |
| 126 | b, err := mobilelink.OpenWorkbench(ctx, s.origin, s.issueTicket()) |
| 127 | if err != nil { |
| 128 | return err |
| 129 | } |
| 130 | defer b.Close() |
| 131 | room, err := mobilelink.CreateDiscoverableRoom(ctx, r.Relay, r.Admin, r.Lookup) |
| 132 | if err != nil { |
| 133 | return err |
| 134 | } |
| 135 | proof := randomToken() |
| 136 | p := &s.phones |
| 137 | p.mu.Lock() |
| 138 | if ctx.Err() != nil || p.closed || p.record == nil || p.record.Lookup != r.Lookup { |
| 139 | p.mu.Unlock() |
| 140 | return context.Canceled |
| 141 | } |
| 142 | roomCtx, cancelRoom := context.WithCancel(ctx) |
| 143 | p.roomProof = proof |
| 144 | p.roomCtx = roomCtx |
| 145 | p.mu.Unlock() |
| 146 | defer func() { |
| 147 | cancelRoom() |
| 148 | p.mu.Lock() |
| 149 | defer p.mu.Unlock() |
| 150 | if p.roomProof == proof { |
| 151 | p.roomProof = "" |
| 152 | p.roomCtx = nil |
| 153 | } |
| 154 | }() |
| 155 | b.SetPhoneRoom(proof) |
| 156 | return mobilelink.ServeHost(ctx, r.Relay, room.ID, room.HostToken, id, r.Pin, b) |
| 157 | } |
| 158 | func (s *Server) stopPhone() { |
| 159 | p := &s.phones |
| 160 | p.mu.Lock() |
| 161 | p.closed = true |
| 162 | p.roomCtx = nil |
| 163 | p.roomProof = "" |
| 164 | if p.pending != nil { |
| 165 | p.pending() |
| 166 | } |
| 167 | if p.serving != nil { |
| 168 | p.serving() |
| 169 | } |
| 170 | done := p.powerDone |
| 171 | p.powerCtx = nil |
| 172 | p.power = keepawake.State{} |
| 173 | p.mu.Unlock() |
| 174 | if done != nil { |
| 175 | <-done |
| 176 | } |
| 177 | } |
| 178 | func (s *Server) phoneStatus(w http.ResponseWriter, r *http.Request) { |
| 179 | p := &s.phones |
| 180 | p.mu.Lock() |
| 181 | defer p.mu.Unlock() |
| 182 | var device *mobilelink.DeviceInfo |
| 183 | if p.record != nil { |
| 184 | device = p.record.Device |
| 185 | } |
| 186 | jsonReply(w, map[string]any{"paired": p.record != nil, "status": p.status, "device": device, "keep_awake": p.power}) |
| 187 | } |
| 188 | |
| 189 | |
| 190 | func (s *Server) reportPhoneDevice(w http.ResponseWriter, r *http.Request) { |
| 191 | var input mobilelink.DeviceInfo |
| 192 | if !readJSON(w, r, &input, 1024) { |
| 193 | return |
| 194 | } |
| 195 | input.Model = strings.TrimSpace(input.Model) |
| 196 | if (input.Platform != "android" && input.Platform != "ios") || input.Model == "" || len(input.Model) > 160 || !utf8.ValidString(input.Model) || strings.ContainsFunc(input.Model, unicode.IsControl) { |
| 197 | http.Error(w, "手机型号无效", http.StatusBadRequest) |
| 198 | return |
| 199 | } |
| 200 | s.account.mu.Lock() |
| 201 | defer s.account.mu.Unlock() |
| 202 | if !s.mobileAuthorized(r.Context()) { |
| 203 | http.Error(w, "请先解锁 Cage", http.StatusLocked) |
| 204 | return |
| 205 | } |
| 206 | p := &s.phones |
| 207 | p.mu.Lock() |
| 208 | defer p.mu.Unlock() |
| 209 | if p.closed || p.record == nil || !p.pairedRequestLocked(r) { |
| 210 | http.Error(w, "请通过已配对的手机连接", http.StatusForbidden) |
| 211 | return |
| 212 | } |
| 213 | if p.record.Device == nil || *p.record.Device != input { |
| 214 | record := *p.record |
| 215 | record.Device = &input |
| 216 | if err := writePrivate(s.phoneFile(), record); err != nil { |
| 217 | requestError(w, err) |
| 218 | return |
| 219 | } |
| 220 | p.record = &record |
| 221 | } |
| 222 | jsonReply(w, map[string]bool{"ok": true}) |
| 223 | } |
| 224 | func (s *Server) removePhone(w http.ResponseWriter, r *http.Request) { |
| 225 | p := &s.phones |
| 226 | p.mu.Lock() |
| 227 | defer p.mu.Unlock() |
| 228 | if p.pending != nil { |
| 229 | p.pending() |
| 230 | p.pending = nil |
| 231 | } |
| 232 | if err := os.Remove(s.phoneFile()); err != nil && !os.IsNotExist(err) { |
| 233 | requestError(w, err) |
| 234 | return |
| 235 | } |
| 236 | if p.serving != nil { |
| 237 | p.serving() |
| 238 | p.serving = nil |
| 239 | } |
| 240 | p.record = nil |
| 241 | p.powerCtx = nil |
| 242 | p.power = keepawake.State{} |
| 243 | p.roomProof = "" |
| 244 | p.roomCtx = nil |
| 245 | p.status = "" |
| 246 | jsonReply(w, map[string]bool{"paired": false}) |
| 247 | } |
| 248 | func (s *Server) pairPhone(w http.ResponseWriter, r *http.Request) { |
| 249 | var input struct { |
| 250 | Admin string `json:"admin"` |
| 251 | Relay string `json:"relay"` |
| 252 | } |
| 253 | if !readJSON(w, r, &input, 8192) { |
| 254 | return |
| 255 | } |
| 256 | epoch, ok := s.account.access() |
| 257 | if !ok { |
| 258 | http.Error(w, "请先解锁 Cage", 423) |
| 259 | return |
| 260 | } |
| 261 | s.mu.Lock() |
| 262 | origin := s.preferences.MobileRelay |
| 263 | s.mu.Unlock() |
| 264 | if origin == "" { |
| 265 | origin = mobilelink.OfficialRelay |
| 266 | } |
| 267 | if input.Admin != "" && (origin == mobilelink.OfficialRelay || origin != input.Relay) { |
| 268 | requestError(w, errors.New("请先保存自建中继地址")) |
| 269 | return |
| 270 | } |
| 271 | p := &s.phones |
| 272 | p.mu.Lock() |
| 273 | if p.closed || p.record != nil { |
| 274 | p.mu.Unlock() |
| 275 | http.Error(w, "请先移除已配对的手机", 409) |
| 276 | return |
| 277 | } |
| 278 | if p.pending != nil { |
| 279 | p.pending() |
| 280 | } |
| 281 | ctx, cancel := context.WithTimeout(epoch, 2*time.Minute) |
| 282 | p.pending = cancel |
| 283 | p.status = "等待扫码" |
| 284 | p.mu.Unlock() |
| 285 | complete := false |
| 286 | defer func() { |
| 287 | if !complete { |
| 288 | cancel() |
| 289 | } |
| 290 | }() |
| 291 | room, err := mobilelink.CreateRoom(ctx, origin, input.Admin) |
| 292 | if err != nil { |
| 293 | requestError(w, errors.New("中继未能创建连接。请检查网络、自建地址和管理令牌。")) |
| 294 | return |
| 295 | } |
| 296 | _, key, err := ed25519.GenerateKey(rand.Reader) |
| 297 | if err != nil { |
| 298 | requestError(w, err) |
| 299 | return |
| 300 | } |
| 301 | host, err := remotelink.IdentityFromKey(key) |
| 302 | if err != nil { |
| 303 | requestError(w, err) |
| 304 | return |
| 305 | } |
| 306 | code, raw, err := mobilelink.NewPairCode(origin, room, host.Pin) |
| 307 | if err != nil { |
| 308 | requestError(w, err) |
| 309 | return |
| 310 | } |
| 311 | png, err := qrcode.Encode(raw, qrcode.Medium, 384) |
| 312 | if err != nil { |
| 313 | requestError(w, errors.New("无法生成二维码")) |
| 314 | return |
| 315 | } |
| 316 | complete = true |
| 317 | go func() { |
| 318 | defer cancel() |
| 319 | err := mobilelink.AcceptPair(ctx, code, room.HostToken, host, func(pin string) (mobilelink.PairedHost, error) { |
| 320 | |
| 321 | |
| 322 | s.account.mu.Lock() |
| 323 | defer s.account.mu.Unlock() |
| 324 | p.mu.Lock() |
| 325 | defer p.mu.Unlock() |
| 326 | var result mobilelink.PairedHost |
| 327 | if ctx.Err() != nil || p.record != nil || p.closed { |
| 328 | return result, errors.New("配对已结束") |
| 329 | } |
| 330 | var token [32]byte |
| 331 | if _, err := rand.Read(token[:]); err != nil { |
| 332 | return result, err |
| 333 | } |
| 334 | record := phoneRecord{Seed: key.Seed(), Relay: origin, Pin: pin, Admin: input.Admin, Lookup: base64.RawURLEncoding.EncodeToString(token[:])} |
| 335 | if err := writePrivate(s.phoneFile(), record); err != nil { |
| 336 | return result, err |
| 337 | } |
| 338 | s.attachPhone(record) |
| 339 | p.status = "手机已配对" |
| 340 | return mobilelink.PairedHost{Version: 1, Relay: origin, HostPin: host.Pin, Lookup: record.Lookup}, nil |
| 341 | }) |
| 342 | p.mu.Lock() |
| 343 | defer p.mu.Unlock() |
| 344 | if err != nil && ctx.Err() == nil && p.record == nil { |
| 345 | p.status = "配对未完成,请重新生成二维码" |
| 346 | } |
| 347 | }() |
| 348 | w.Header().Set("Cache-Control", "no-store") |
| 349 | jsonReply(w, map[string]any{"image": "data:image/png;base64," + base64.StdEncoding.EncodeToString(png), "expires": room.ExpiresAt, "manual": "CAGE-" + base64.RawURLEncoding.EncodeToString([]byte(raw))}) |
| 350 | } |