| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "archive/zip" |
| 5 | "bytes" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "net/http" |
| 14 | "os" |
| 15 | "path/filepath" |
| 16 | "runtime" |
| 17 | "sort" |
| 18 | "strings" |
| 19 | ) |
| 20 | |
| 21 | type localBrowserRoot struct{ Name, Path string } |
| 22 | type localBrowserExtension struct { |
| 23 | ID string `json:"id"` |
| 24 | Name string `json:"name"` |
| 25 | Version string `json:"version"` |
| 26 | Enabled bool `json:"enabled"` |
| 27 | StateKnown bool `json:"state_known"` |
| 28 | Compatible bool `json:"compatible"` |
| 29 | IdentityPreserved bool `json:"identity_preserved"` |
| 30 | Permissions []string `json:"permissions"` |
| 31 | HostPermissions []string `json:"hostPermissions"` |
| 32 | directory string |
| 33 | key string |
| 34 | } |
| 35 | type localBrowserProfile struct { |
| 36 | ID string `json:"id"` |
| 37 | Browser string `json:"browser"` |
| 38 | Name string `json:"name"` |
| 39 | Extensions []localBrowserExtension `json:"extensions"` |
| 40 | } |
| 41 | |
| 42 | func localBrowserRoots() []localBrowserRoot { |
| 43 | home, _ := os.UserHomeDir() |
| 44 | var base string |
| 45 | var locations []string |
| 46 | switch runtime.GOOS { |
| 47 | case "darwin": |
| 48 | base = filepath.Join(home, "Library", "Application Support") |
| 49 | locations = []string{"Microsoft Edge", "Google/Chrome", "BraveSoftware/Brave-Browser", "Chromium"} |
| 50 | case "windows": |
| 51 | base = os.Getenv("LOCALAPPDATA") |
| 52 | locations = []string{"Microsoft/Edge/User Data", "Google/Chrome/User Data", "BraveSoftware/Brave-Browser/User Data", "Chromium/User Data"} |
| 53 | default: |
| 54 | base, _ = os.UserConfigDir() |
| 55 | locations = []string{"microsoft-edge", "google-chrome", "BraveSoftware/Brave-Browser", "chromium"} |
| 56 | } |
| 57 | if base == "" { |
| 58 | return nil |
| 59 | } |
| 60 | var roots []localBrowserRoot |
| 61 | for i, name := range []string{"Microsoft Edge", "Google Chrome", "Brave", "Chromium"} { |
| 62 | roots = append(roots, localBrowserRoot{name, filepath.Join(base, filepath.FromSlash(locations[i]))}) |
| 63 | } |
| 64 | return roots |
| 65 | } |
| 66 | func readBrowserJSON(path string, value any) bool { |
| 67 | info, err := os.Lstat(path) |
| 68 | if err != nil || !info.Mode().IsRegular() || info.Size() > 16<<20 { |
| 69 | return false |
| 70 | } |
| 71 | file, err := os.Open(path) |
| 72 | if err != nil { |
| 73 | return false |
| 74 | } |
| 75 | defer file.Close() |
| 76 | return json.NewDecoder(io.LimitReader(file, 16<<20)).Decode(value) == nil |
| 77 | } |
| 78 | func browserDirectory(path string) bool { |
| 79 | info, err := os.Lstat(path) |
| 80 | return err == nil && info.IsDir() && info.Mode()&os.ModeSymlink == 0 |
| 81 | } |
| 82 | |
| 83 | func scanLocalBrowserProfiles(roots []localBrowserRoot) []localBrowserProfile { |
| 84 | result := []localBrowserProfile{} |
| 85 | for _, root := range roots { |
| 86 | if !browserDirectory(root.Path) { |
| 87 | continue |
| 88 | } |
| 89 | entries, err := os.ReadDir(root.Path) |
| 90 | if err != nil { |
| 91 | continue |
| 92 | } |
| 93 | var local struct { |
| 94 | Profile struct { |
| 95 | Info map[string]struct { |
| 96 | Name string `json:"name"` |
| 97 | } `json:"info_cache"` |
| 98 | } `json:"profile"` |
| 99 | } |
| 100 | readBrowserJSON(filepath.Join(root.Path, "Local State"), &local) |
| 101 | for _, entry := range entries { |
| 102 | name := entry.Name() |
| 103 | if name != "Default" && !strings.HasPrefix(name, "Profile ") { |
| 104 | continue |
| 105 | } |
| 106 | profilePath := filepath.Join(root.Path, name) |
| 107 | if !browserDirectory(profilePath) { |
| 108 | continue |
| 109 | } |
| 110 | digest := sha256.Sum256([]byte(root.Path + "\x00" + name)) |
| 111 | profile := localBrowserProfile{ID: hex.EncodeToString(digest[:16]), Browser: root.Name, Name: local.Profile.Info[name].Name, Extensions: []localBrowserExtension{}} |
| 112 | if profile.Name == "" { |
| 113 | profile.Name = name |
| 114 | } |
| 115 | var prefs struct { |
| 116 | Extensions struct { |
| 117 | Settings map[string]struct { |
| 118 | State *int `json:"state"` |
| 119 | DisableReasons json.RawMessage `json:"disable_reasons"` |
| 120 | Path string `json:"path"` |
| 121 | Manifest struct { |
| 122 | Key string `json:"key"` |
| 123 | } `json:"manifest"` |
| 124 | } `json:"settings"` |
| 125 | } `json:"extensions"` |
| 126 | } |
| 127 | readBrowserJSON(filepath.Join(profilePath, "Preferences"), &prefs) |
| 128 | |
| 129 | var secure = prefs |
| 130 | if readBrowserJSON(filepath.Join(profilePath, "Secure Preferences"), &secure) { |
| 131 | for id, value := range secure.Extensions.Settings { |
| 132 | if prefs.Extensions.Settings == nil { |
| 133 | prefs.Extensions.Settings = secure.Extensions.Settings |
| 134 | break |
| 135 | } |
| 136 | prefs.Extensions.Settings[id] = value |
| 137 | } |
| 138 | } |
| 139 | extRoot := filepath.Join(profilePath, "Extensions") |
| 140 | if !browserDirectory(extRoot) { |
| 141 | continue |
| 142 | } |
| 143 | extensionDirs, _ := os.ReadDir(extRoot) |
| 144 | for _, extensionDir := range extensionDirs { |
| 145 | id := extensionDir.Name() |
| 146 | if len(id) != 32 || strings.Trim(id, "abcdefghijklmnop") != "" { |
| 147 | continue |
| 148 | } |
| 149 | directory := filepath.Join(extRoot, id) |
| 150 | if !browserDirectory(directory) { |
| 151 | continue |
| 152 | } |
| 153 | versions, _ := os.ReadDir(directory) |
| 154 | sort.Slice(versions, func(i, j int) bool { |
| 155 | a, _ := versions[i].Info() |
| 156 | b, _ := versions[j].Info() |
| 157 | return a != nil && (b == nil || a.ModTime().After(b.ModTime())) |
| 158 | }) |
| 159 | state := prefs.Extensions.Settings[id] |
| 160 | if _, registered := prefs.Extensions.Settings[id]; prefs.Extensions.Settings != nil && !registered { |
| 161 | continue |
| 162 | } |
| 163 | if state.State != nil && *state.State == 2 { |
| 164 | continue |
| 165 | } |
| 166 | if state.Path != "" { |
| 167 | desired := filepath.Base(filepath.Clean(state.Path)) |
| 168 | sort.SliceStable(versions, func(i, j int) bool { return versions[i].Name() == desired && versions[j].Name() != desired }) |
| 169 | } |
| 170 | for _, version := range versions { |
| 171 | packagePath := filepath.Join(directory, version.Name()) |
| 172 | if !browserDirectory(packagePath) { |
| 173 | continue |
| 174 | } |
| 175 | var manifest struct { |
| 176 | Name string `json:"name"` |
| 177 | Version string `json:"version"` |
| 178 | ManifestVersion int `json:"manifest_version"` |
| 179 | Key string `json:"key"` |
| 180 | Permissions []string `json:"permissions"` |
| 181 | Hosts []string `json:"host_permissions"` |
| 182 | Content []struct { |
| 183 | Matches []string `json:"matches"` |
| 184 | } `json:"content_scripts"` |
| 185 | Locale string `json:"default_locale"` |
| 186 | } |
| 187 | if !readBrowserJSON(filepath.Join(packagePath, "manifest.json"), &manifest) || manifest.Name == "" || manifest.Version == "" { |
| 188 | continue |
| 189 | } |
| 190 | display := manifest.Name |
| 191 | if strings.HasPrefix(display, "__MSG_") && strings.HasSuffix(display, "__") && filepath.Base(manifest.Locale) == manifest.Locale { |
| 192 | var messages map[string]struct { |
| 193 | Message string `json:"message"` |
| 194 | } |
| 195 | if readBrowserJSON(filepath.Join(packagePath, "_locales", manifest.Locale, "messages.json"), &messages) { |
| 196 | if text := messages[strings.TrimSuffix(strings.TrimPrefix(display, "__MSG_"), "__")].Message; text != "" { |
| 197 | display = text |
| 198 | } |
| 199 | } |
| 200 | } |
| 201 | publicKey := manifest.Key |
| 202 | if publicKey == "" { |
| 203 | publicKey = state.Manifest.Key |
| 204 | } |
| 205 | if publicKey != "" { |
| 206 | data, decodeErr := base64.StdEncoding.DecodeString(publicKey) |
| 207 | digest := sha256.Sum256(data) |
| 208 | actual := "" |
| 209 | for _, char := range hex.EncodeToString(digest[:16]) { |
| 210 | var value int |
| 211 | if char >= 'a' { |
| 212 | value = int(char-'a') + 10 |
| 213 | } else { |
| 214 | value = int(char - '0') |
| 215 | } |
| 216 | actual += string(rune('a' + value)) |
| 217 | } |
| 218 | if decodeErr != nil || actual != id { |
| 219 | publicKey = "" |
| 220 | } |
| 221 | } |
| 222 | enabled, known := importedExtensionState(state.State, state.DisableReasons) |
| 223 | hosts := append([]string{}, manifest.Hosts...) |
| 224 | for _, content := range manifest.Content { |
| 225 | hosts = append(hosts, content.Matches...) |
| 226 | } |
| 227 | profile.Extensions = append(profile.Extensions, localBrowserExtension{ID: id, Name: display, Version: manifest.Version, Enabled: enabled, StateKnown: known, Compatible: manifest.ManifestVersion == 3, IdentityPreserved: publicKey != "", Permissions: manifest.Permissions, HostPermissions: hosts, directory: packagePath, key: publicKey}) |
| 228 | break |
| 229 | } |
| 230 | } |
| 231 | sort.Slice(profile.Extensions, func(i, j int) bool { return profile.Extensions[i].Name < profile.Extensions[j].Name }) |
| 232 | result = append(result, profile) |
| 233 | } |
| 234 | } |
| 235 | return result |
| 236 | } |
| 237 | |
| 238 | |
| 239 | func importedExtensionState(state *int, reasons json.RawMessage) (bool, bool) { |
| 240 | if len(reasons) > 0 && string(reasons) != "null" { |
| 241 | var list []json.RawMessage |
| 242 | if json.Unmarshal(reasons, &list) == nil { |
| 243 | return len(list) == 0 && (state == nil || *state == 1), true |
| 244 | } |
| 245 | var mask int |
| 246 | if json.Unmarshal(reasons, &mask) == nil { |
| 247 | return mask == 0 && (state == nil || *state == 1), true |
| 248 | } |
| 249 | } |
| 250 | if state != nil { |
| 251 | return *state == 1, true |
| 252 | } |
| 253 | return false, false |
| 254 | } |
| 255 | |
| 256 | func packageLocalExtension(extension localBrowserExtension) ([]byte, error) { |
| 257 | if !extension.Compatible || !browserDirectory(extension.directory) { |
| 258 | return nil, errors.New("此扩展不支持导入") |
| 259 | } |
| 260 | var output bytes.Buffer |
| 261 | archive := zip.NewWriter(&output) |
| 262 | count := 0 |
| 263 | var total int64 |
| 264 | err := filepath.WalkDir(extension.directory, func(path string, entry os.DirEntry, walkErr error) error { |
| 265 | if walkErr != nil { |
| 266 | return walkErr |
| 267 | } |
| 268 | relative, e := filepath.Rel(extension.directory, path) |
| 269 | if e != nil { |
| 270 | return e |
| 271 | } |
| 272 | if relative == "." { |
| 273 | return nil |
| 274 | } |
| 275 | if entry.IsDir() { |
| 276 | if entry.Name() == "_metadata" || entry.Name() == ".git" { |
| 277 | return filepath.SkipDir |
| 278 | } |
| 279 | return nil |
| 280 | } |
| 281 | info, e := entry.Info() |
| 282 | if e != nil { |
| 283 | return e |
| 284 | } |
| 285 | if !info.Mode().IsRegular() || entry.Type()&os.ModeSymlink != 0 { |
| 286 | return errors.New("扩展包含无法导入的特殊文件") |
| 287 | } |
| 288 | count++ |
| 289 | total += info.Size() |
| 290 | if count > 3000 || total > 128<<20 || info.Size() > 32<<20 { |
| 291 | return errors.New("扩展文件超出导入限制") |
| 292 | } |
| 293 | target, e := archive.Create(filepath.ToSlash(relative)) |
| 294 | if e != nil { |
| 295 | return e |
| 296 | } |
| 297 | source, e := os.Open(path) |
| 298 | if e != nil { |
| 299 | return e |
| 300 | } |
| 301 | defer source.Close() |
| 302 | if relative == "manifest.json" && extension.key != "" { |
| 303 | var manifest map[string]any |
| 304 | if json.NewDecoder(io.LimitReader(source, 1<<20)).Decode(&manifest) != nil { |
| 305 | return errors.New("扩展配置已变化,请刷新清单") |
| 306 | } |
| 307 | manifest["key"] = extension.key |
| 308 | return json.NewEncoder(target).Encode(manifest) |
| 309 | } |
| 310 | _, e = io.CopyN(target, source, info.Size()) |
| 311 | if output.Len() > 32<<20 { |
| 312 | return errors.New("扩展压缩包不能超过 32 MB") |
| 313 | } |
| 314 | return e |
| 315 | }) |
| 316 | closeErr := archive.Close() |
| 317 | if err != nil { |
| 318 | return nil, err |
| 319 | } |
| 320 | if closeErr != nil { |
| 321 | return nil, closeErr |
| 322 | } |
| 323 | if output.Len() > 32<<20 { |
| 324 | return nil, errors.New("扩展压缩包不能超过 32 MB") |
| 325 | } |
| 326 | return output.Bytes(), nil |
| 327 | } |
| 328 | |
| 329 | func (s *Server) localBrowserExtensions(w http.ResponseWriter, r *http.Request) { |
| 330 | profiles := scanLocalBrowserProfiles(localBrowserRoots()) |
| 331 | if r.Method == http.MethodGet { |
| 332 | jsonReply(w, map[string]any{"profiles": profiles}) |
| 333 | return |
| 334 | } |
| 335 | var input struct { |
| 336 | Profile string `json:"profile"` |
| 337 | ID string `json:"id"` |
| 338 | Version string `json:"version"` |
| 339 | } |
| 340 | if !readJSON(w, r, &input) { |
| 341 | return |
| 342 | } |
| 343 | for _, profile := range profiles { |
| 344 | if profile.ID != input.Profile { |
| 345 | continue |
| 346 | } |
| 347 | for _, extension := range profile.Extensions { |
| 348 | if extension.ID != input.ID { |
| 349 | continue |
| 350 | } |
| 351 | if extension.Version != input.Version { |
| 352 | requestError(w, errors.New("本机扩展已更新,请刷新清单")) |
| 353 | return |
| 354 | } |
| 355 | data, err := packageLocalExtension(extension) |
| 356 | if err != nil { |
| 357 | requestError(w, err) |
| 358 | return |
| 359 | } |
| 360 | w.Header().Set("Content-Type", "application/zip") |
| 361 | w.Header().Set("Content-Length", fmt.Sprint(len(data))) |
| 362 | _, _ = w.Write(data) |
| 363 | return |
| 364 | } |
| 365 | } |
| 366 | http.Error(w, "所选本机扩展已不可用,请刷新清单", http.StatusNotFound) |
| 367 | } |