| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "path/filepath" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/sylvinus/agent-vm/internal/containerenv" |
| 14 | ) |
| 15 | |
| 16 | var ( |
| 17 | errBrowserNotReady = errors.New("环境尚未就绪") |
| 18 | errBrowserBusy = errors.New("环境正在执行其他操作") |
| 19 | ) |
| 20 | |
| 21 | type browserInputError struct{ error } |
| 22 | |
| 23 | type browserInput struct { |
| 24 | Incognito bool `json:"incognito,omitempty"` |
| 25 | Enabled *bool `json:"enabled,omitempty"` |
| 26 | CookieKey string `json:"cookieKey,omitempty"` |
| 27 | Scope string `json:"scope,omitempty"` |
| 28 | Query string `json:"query,omitempty"` |
| 29 | Page int `json:"page,omitempty"` |
| 30 | Left string `json:"left,omitempty"` |
| 31 | Right string `json:"right,omitempty"` |
| 32 | ID string `json:"id"` |
| 33 | URL string `json:"url"` |
| 34 | Width int `json:"width,omitempty"` |
| 35 | Height int `json:"height,omitempty"` |
| 36 | Scale float64 `json:"scale,omitempty"` |
| 37 | Workspace string `json:"workspace,omitempty"` |
| 38 | ProjectID string `json:"project_id,omitempty"` |
| 39 | ProjectGrant string `json:"grant,omitempty"` |
| 40 | Text string `json:"text,omitempty"` |
| 41 | Mode string `json:"mode,omitempty"` |
| 42 | Target string `json:"target,omitempty"` |
| 43 | Session string `json:"session,omitempty"` |
| 44 | Context string `json:"context,omitempty"` |
| 45 | Sequence int `json:"sequence"` |
| 46 | SelectionStart int `json:"selectionStart,omitempty"` |
| 47 | SelectionEnd int `json:"selectionEnd,omitempty"` |
| 48 | } |
| 49 | |
| 50 | func (s *Server) browserClient() *browserClient { |
| 51 | s.mu.Lock() |
| 52 | defer s.mu.Unlock() |
| 53 | if s.browserControl == nil { |
| 54 | s.browserControl = newBrowserClient(s.lifetimeContextLocked()) |
| 55 | transport := s.browserControl.http.Transport.(*http.Transport) |
| 56 | lifetime := s.browserControl.ctx |
| 57 | if containerenv.Configured(s.profile) { |
| 58 | transport.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { |
| 59 | environment, err := containerenv.Load(s.profile) |
| 60 | if err != nil { |
| 61 | return nil, err |
| 62 | } |
| 63 | state, err := environment.State(ctx) |
| 64 | if err != nil { |
| 65 | return nil, err |
| 66 | } |
| 67 | if !state.Ready { |
| 68 | return nil, errBrowserNotReady |
| 69 | } |
| 70 | return (&net.Dialer{Timeout: 3 * time.Second}).DialContext(ctx, network, state.BrowserAddress) |
| 71 | } |
| 72 | } else { |
| 73 | transport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) { |
| 74 | return s.dialGuestBrowser(ctx, lifetime) |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | return s.browserControl |
| 79 | } |
| 80 | |
| 81 | func (s *Server) guestAPI(ctx context.Context, token, method, path string, body []byte) ([]byte, error) { |
| 82 | if s.macosGuest != nil || s.windowsGuest != nil { |
| 83 | return s.nativeBrowserAPI(ctx, method, path, body) |
| 84 | } |
| 85 | return s.browserClient().request(ctx, token, method, path, body) |
| 86 | } |
| 87 | |
| 88 | func (s *Server) setBrowserHome(ctx context.Context, token, home string) error { |
| 89 | body, _ := json.Marshal(map[string]string{"url": home}) |
| 90 | _, err := s.guestAPI(ctx, token, http.MethodPost, "/homepage", body) |
| 91 | return err |
| 92 | } |
| 93 | |
| 94 | func (s *Server) browserAction(ctx context.Context, action string, input *browserInput) ([]byte, error) { |
| 95 | s.mu.Lock() |
| 96 | ready, token := s.ready, s.credentials.Token |
| 97 | s.mu.Unlock() |
| 98 | if !ready { |
| 99 | return nil, errBrowserNotReady |
| 100 | } |
| 101 | method := http.MethodGet |
| 102 | var body []byte |
| 103 | if input != nil { |
| 104 | method = http.MethodPost |
| 105 | if action == "download-retry" && (s.macosGuest != nil || s.windowsGuest != nil) { |
| 106 | if handled, err := s.retryNativeDownload(input.ID); handled { |
| 107 | return []byte(`{"ok":true}`), err |
| 108 | } |
| 109 | } |
| 110 | if action == "cookies" && (input.ID == "" || |
| 111 | (input.Mode != "list" && input.Mode != "details" && input.Mode != "delete" && input.Mode != "clear") || |
| 112 | (input.Scope != "site" && input.Scope != "all") || len(input.Query) > 800 || input.Page < 0 || |
| 113 | ((input.Mode == "delete" || input.Mode == "details") && len(input.CookieKey) != 64)) { |
| 114 | return nil, browserInputError{errors.New("Cookie 操作或目标标签无效")} |
| 115 | } |
| 116 | if (action == "copy-context" || action == "copy" || action == "cut") && (input.ID == "" || !validInputToken(input.Context)) { |
| 117 | return nil, browserInputError{errors.New("复制操作或目标标签无效")} |
| 118 | } |
| 119 | if action == "resize" && !validDisplayDensity(input.Scale) { |
| 120 | return nil, browserInputError{errors.New("画面像素密度无效")} |
| 121 | } |
| 122 | if action == "insert-text" && (input.ID == "" || input.Text == "" || len(input.Text) > 8192) { |
| 123 | return nil, browserInputError{errors.New("输入文字或目标标签无效")} |
| 124 | } |
| 125 | if action == "ime" { |
| 126 | selectionLimit := 0 |
| 127 | for _, char := range input.Text { |
| 128 | selectionLimit++ |
| 129 | if char > 0xffff { |
| 130 | selectionLimit++ |
| 131 | } |
| 132 | } |
| 133 | validMode := input.Mode == "status" || input.Mode == "begin" || input.Mode == "update" || input.Mode == "commit" || input.Mode == "cancel" |
| 134 | validTarget := input.Target == "browser" && input.ID != "" || input.Target == "desktop" && input.ID == "desktop" |
| 135 | validSession := input.Mode == "status" || validInputToken(input.Session) |
| 136 | if !validTarget || !validMode || !validSession || input.Mode == "begin" && !validInputToken(input.Context) || input.Sequence < 0 || len(input.Text) > 8192 || input.SelectionStart < 0 || input.SelectionEnd < input.SelectionStart || input.SelectionEnd > selectionLimit { |
| 137 | return nil, browserInputError{errors.New("输入法组合状态无效")} |
| 138 | } |
| 139 | } |
| 140 | if action == "new" && input.URL == "" { |
| 141 | s.mu.Lock() |
| 142 | input.URL = browserHomeURL(s.preferences) |
| 143 | s.mu.Unlock() |
| 144 | } |
| 145 | if action == "editor" || action == "editor-restart" { |
| 146 | if !s.op.TryLock() { |
| 147 | return nil, errBrowserBusy |
| 148 | } |
| 149 | defer s.op.Unlock() |
| 150 | s.mu.Lock() |
| 151 | closing := s.closing |
| 152 | s.mu.Unlock() |
| 153 | if closing { |
| 154 | return nil, errJobsClosed |
| 155 | } |
| 156 | workspace, err := s.connectProject(input.Workspace, false) |
| 157 | if err != nil { |
| 158 | return nil, browserInputError{err} |
| 159 | } |
| 160 | input.Workspace = guestPath(workspace) |
| 161 | if s.macosGuest != nil { |
| 162 | if isClientMountPath(workspace) { |
| 163 | return nil, browserInputError{errors.New("请先打开并授权本机项目")} |
| 164 | } |
| 165 | input.Workspace = filepath.Base(macOSProjectPath(s.macosGuest.User, workspace)) |
| 166 | } else if s.windowsGuest != nil { |
| 167 | project, err := s.windowsProjectForHost(workspace) |
| 168 | if err != nil { |
| 169 | return nil, browserInputError{err} |
| 170 | } |
| 171 | input.Workspace = project.Path |
| 172 | input.ProjectID = project.ID |
| 173 | input.ProjectGrant = project.Grant |
| 174 | } |
| 175 | } |
| 176 | body, _ = json.Marshal(input) |
| 177 | } |
| 178 | data, err := s.guestAPI(ctx, token, method, "/"+action, body) |
| 179 | if err != nil { |
| 180 | return nil, err |
| 181 | } |
| 182 | if action == "tabs" { |
| 183 | data, err = s.browserStateForHost(data) |
| 184 | } |
| 185 | if len(data) > browserResponseLimit { |
| 186 | return nil, errors.New("浏览器响应超出大小限制") |
| 187 | } |
| 188 | return data, err |
| 189 | } |
| 190 | |
| 191 | func validInputToken(value string) bool { |
| 192 | if len(value) != 32 { |
| 193 | return false |
| 194 | } |
| 195 | for _, char := range value { |
| 196 | if !(char >= '0' && char <= '9' || char >= 'a' && char <= 'f') { |
| 197 | return false |
| 198 | } |
| 199 | } |
| 200 | return true |
| 201 | } |
| 202 | |
| 203 | func (s *Server) subscribeBrowser(ctx context.Context) (io.ReadCloser, error) { |
| 204 | s.mu.Lock() |
| 205 | ready, token := s.ready, s.credentials.Token |
| 206 | s.mu.Unlock() |
| 207 | if !ready { |
| 208 | return nil, errBrowserNotReady |
| 209 | } |
| 210 | if s.macosGuest != nil || s.windowsGuest != nil { |
| 211 | return s.subscribeNativeBrowser(ctx), nil |
| 212 | } |
| 213 | return s.browserClient().events(ctx, token) |
| 214 | } |