| 1 | |
| 2 | |
| 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 | |
| 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 | |
| 115 | |
| 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 | |
| 133 | |
| 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 |
| 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 | } |