Files
magpie/internal/gui/browser.go
T
yetone 483b131ef0 browser: magpie in Docker uses the host's own browser, through a key the page hands out
noahhrreion ran magpie in a container and its Magpie Browser never
connected. The host's Chrome dials ws://127.0.0.1:3425/v1/magpie/browser/
extension, which reaches the container from the bridge (172.17.0.1). That
is not loopback, so the gateway refused it (403). The browser MCP also
refused every caller from elsewhere, and the hub marked the browser
HereOnly. The extension's folder under the container's HOME can't be
loaded by the host's browser either.

Nothing is opened to the network without a key:

- The extension takes a gateway key: its popup has a Gateway key field,
  and config.js carries KEY (extension 0.1.7). From another computer the
  extension connects only with ?key= of a gateway key that is on, and
  only from the extension's own Origin (checked first). Loopback is
  unchanged, and a page's origin, null, a keyless call or a rebound Host
  are all still refused (TestBrowserExtensionOnlyFromItsOrigin).
- A browser that connects with a key belongs to that key. Sessions are
  tagged key:<id>/... (browserOwner, keyedSession), and a remote caller's
  session is forced to its own key's whatever it names. The relay filters
  every lookup (forSession, all, choose) through browserConn.serves. The
  browser MCP admits a remote caller only with a gateway key; a web page
  is refused as before.
- The key the page makes is recorded as this magpie's own browser's: its
  id goes in settings.Dir()/browser-key, written temp-and-rename. This
  goes by where the key came from, not by its name. A browser connecting
  with it serves this computer's sessions too, so agents inside the
  container use it as they would one on loopback. A record that can't be
  read names no key, so no keyed browser is this computer's.
- Router: magpie mcp browser is HubServer.Keyed. A visitor from
  elsewhere gets it only with a key (HubVisitor.Key), and hubCall names
  its session key:<id>/..., so it reaches only that key's browser.
- GUI: a page whose browser can't reach magpie's folders (InContainer, or
  a page from another computer) is "away". The Magpie Browser sheet's
  button then reads Download the extension. It does a POST to
  /api/library/browser/extension with the page's origin, which answers a
  zip pointed at that origin (3430 passes the gateway's routes on) and
  holding the recorded key's secret. The key is made the first time and
  reused while it is on. The steps (unzip, chrome://extensions, Developer
  mode, Load unpacked) are shown in every language. It is a POST so that
  a link from another site can't mint a key.
- Docs: reference.md (Docker), subsystems/library.md and mcp-router.md,
  and site docker.html in en, zh and ja.

Run, at this tree rebased on origin/main 6302f88bf, on mote:
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., and darwin, linux and windows builds:
  clean, all ok
- go test -tags nogui -run 'Browser|Hub|OwnBrowser' ./internal/gateway/,
  and the whole of internal/library, internal/gui and internal/browserext:
  ok (gateway 2.4s, library 166s, gui 104s, browserext 0.3s)
- GUI tests library-browser-away (new: every language, Chromium and
  WebKit, 1100 and 420 wide), library-browser-setup, library-browser-ask,
  i18n-keys and i18n-en-no-cjk: 115 pass. One red, i18n-keys "a plugin's words are its own", is for three
  strings this change doesn't touch and is already filed (#5332, #5426,
  #5482)

Real use, in Docker Desktop on xiaomi-gpu (Windows 11): this tree's
Dockerfile image, run as `web --addr 0.0.0.0:3430` with 3425 and 3430
published to the host's localhost. The host's Node and Playwright Chromium:
- signed in to the page, which says away:true;
- downloaded the zip (GATEWAY "ws://localhost:3530" and a KEY), twice,
  getting the same key both times;
- a keyless /mcp/magpie/browser call from the host got 401;
- loaded the unzipped extension with --load-extension. The container's log
  says "Magpie Browser 0.1.7 connected with gateway key 12d2702a…" and
  /api/library/browser says connected:true;
- an MCP client on the host with that key listed b1 (Chrome 151), opened
  http://localhost:3531/ (served on the host) and read "hello from the
  host";
- a second gateway key made in the container got "isn't connected with
  this gateway key";
- a curl inside the container to 127.0.0.1:3425/mcp/magpie/browser with no
  key listed the host browser's tabs, the host page included.

Broken by hand, each red:
- forSession left unfiltered;
- a remote session not forced to its key;
- no Origin check on a keyed connect;
- hubCall not prefixing the session;
- Keyed given to a visitor with no key;
- the old MCP guard;
- browserKey not reusing the key;
- the away peer check removed;
- serves("") without own (TestOwnBrowserKeyIsThisComputers,
  TestOwnBrowserKeyUnreadable);
- OwnBrowserKey reading the wrong file (the gateway tests and
  TestBrowserExtensionDownload).

Not tried:
- the reporter's own setup (their compose file and Chrome);
- a real agent's MCP client calling the browser from the host. Node's
  fetch sends Sec-Fetch-Mode: cors, which fromBrowser counts as a web page
  and refuses. The e2e used node's http instead. Whether an agent's MCP
  client built on fetch is hit by this is not checked; filed as #5522.
- Edge, Brave and Firefox;
- a remote page over https/wss through a proxy.

What the user does: update magpie and publish 3425 and 3430. In the web
UI open Library -> Magpie Browser -> Download the extension, unzip it and
Load unpacked in chrome://extensions. An extension 0.1.7 already loaded
can take the address and key in its popup instead.

Reported-by: noahhrreion (Discord)
2026-11-06 20:06:15 +08:00

202 lines
6.8 KiB
Go

package gui
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/browserext"
"github.com/yetone/magpie/internal/gateway"
)
// Magpie Browser's extension, as the Library page sets it up: written to a
// folder the user can see, in their home folder, which they drop on their
// own browser's chrome://extensions (or choose with Load unpacked), and
// connected or not as the gateway says.
// the folders it is written to (browserext.Dir, and OldDir while a
// browser still loads it from there)
func browserExtDir() string { return browserext.Dir() }
func browserExtOldDir() string { return browserext.OldDir() }
type browserJSON struct {
Dir string `json:"dir"`
Written bool `json:"written"`
Version string `json:"version"`
Connected bool `json:"connected"`
Extension string `json:"extension,omitempty"` // the connected one's version
Browser string `json:"browser,omitempty"`
// Drag: the page may drag the folder out of the window itself
Drag bool `json:"drag,omitempty"`
// Away: the page is looked at from another computer than magpie's, or
// magpie runs in a container, so the folder magpie writes is out of
// the browser's reach; the extension is downloaded instead, with a
// gateway key of its own (browserKey)
Away bool `json:"away,omitempty"`
}
// browserAway is whether r's page is in a browser magpie's folders are out
// of reach of (browserJSON's Away).
func browserAway(r *http.Request) bool {
return gateway.InContainer() || !loopbackPeer(r.RemoteAddr)
}
// browserKeyName names the gateway key a downloaded extension connects with.
const browserKeyName = "Magpie Browser"
// browserKey is the secret of the gateway key a downloaded extension
// connects with: the one recorded as the user's own browser's
// (gateway.OwnBrowserKey) while it is on, else a new one, recorded. The
// browser it connects is used by that key's callers and by this
// computer's (gateway/browser.go), not by another key's.
func browserKey() (string, error) {
if id := gateway.OwnBrowserKey(); id != "" && access.On(id) {
if secret, err := access.Update("copy-key", access.Change{Key: id}); err == nil && secret != "" {
return secret, nil
}
}
secret, err := access.Update("add-key", access.Change{Name: browserKeyName})
if err != nil {
return "", err
}
who, ok := access.Authenticate(secret)
if !ok {
return "", errors.New("the key made for the extension isn't on")
}
// this computer's agents use the browser that connects with it, as
// they do one on loopback
if err := gateway.SetOwnBrowserKey(who.KeyID); err != nil {
return "", err
}
return secret, nil
}
// browserAt is the gateway address a downloaded extension dials: the
// page's own (at, its origin, whose port hands the gateway's routes on,
// onePort), else MAGPIE_PUBLIC_URL, else the gateway's.
func browserAt(at string) (string, error) {
if at == "" {
if u := gateway.PublicURL(); u != "" {
return u, nil
}
return gateway.URL(), nil
}
u, err := url.Parse(at)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" {
return "", errors.New("the extension's gateway is an http or https origin, such as http://localhost:3430")
}
return u.Scheme + "://" + u.Host, nil
}
func browserState(ctx context.Context) browserJSON {
out := browserJSON{Dir: browserExtDir(), Version: browserext.Version(), Drag: canDragFile}
for _, dir := range []string{out.Dir, browserExtOldDir()} {
if _, err := os.Stat(filepath.Join(dir, "manifest.json")); err == nil {
out.Written = out.Written || dir == out.Dir
// kept as this magpie has it, and pointed at its gateway: the
// browser reads the folder again when it starts
browserext.Write(dir, gateway.URL())
}
}
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, gateway.URL()+gateway.BrowserStatusPath, nil)
if err != nil {
return out
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return out
}
defer resp.Body.Close()
var st struct {
Connected bool `json:"connected"`
Extension string `json:"extension"`
Browser string `json:"browser"`
}
if resp.StatusCode == http.StatusOK && json.NewDecoder(resp.Body).Decode(&st) == nil {
out.Connected, out.Extension, out.Browser = st.Connected, st.Extension, st.Browser
}
return out
}
func browserRoutes(mux *http.ServeMux, w Windows) {
mux.HandleFunc("GET /api/library/browser", func(rw http.ResponseWriter, r *http.Request) {
st := browserState(r.Context())
st.Away = browserAway(r)
writeJSON(rw, st)
})
// the extension as a zip, for a browser magpie's folders are out of
// reach of (browserJSON's Away): pointed at the page's own address,
// and given a gateway key of its own
mux.HandleFunc("POST /api/library/browser/extension", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
At string `json:"at"`
}
if r.Body != nil {
json.NewDecoder(http.MaxBytesReader(rw, r.Body, 4<<10)).Decode(&in)
}
at, err := browserAt(in.At)
if err != nil {
http.Error(rw, err.Error(), http.StatusBadRequest)
return
}
key, err := browserKey()
if err != nil {
fail(rw, err)
return
}
b, err := browserext.Zip(at, key)
if err != nil {
fail(rw, err)
return
}
rw.Header().Set("Content-Type", "application/zip")
rw.Header().Set("Content-Disposition", `attachment; filename="`+browserext.Folder+`.zip"`)
rw.Header().Set("Cache-Control", "no-store")
rw.Write(b)
})
// Set up: the extension written, and its folder shown selected, to
// drag onto the browser's extensions page or choose with Load unpacked
mux.HandleFunc("POST /api/library/browser/setup", func(rw http.ResponseWriter, r *http.Request) {
dir := browserExtDir()
if err := browserext.Write(dir, gateway.URL()); err != nil {
fail(rw, err)
return
}
st := browserState(r.Context())
var reveal string
if err := revealIn(w, dir); err != nil {
reveal = err.Error()
}
writeJSON(rw, struct {
browserJSON
RevealError string `json:"revealError,omitempty"`
}{st, reveal})
})
// the folder dragged out of the window, as the page's mouse drags it
mux.HandleFunc("POST /api/library/browser/drag", func(rw http.ResponseWriter, r *http.Request) {
dir := browserExtDir()
if err := browserext.Write(dir, gateway.URL()); err != nil {
fail(rw, err)
return
}
writeJSON(rw, map[string]bool{"dragging": dragFile(dir)})
})
}
// revealIn shows path selected in its parent folder where the host can,
// and opens it where it can't.
func revealIn(w Windows, path string) error {
if r, ok := w.(interface{ RevealFolder(string) error }); ok {
return r.RevealFolder(path)
}
return w.OpenFolder(path)
}