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)
This commit is contained in:
yetone
2026-11-06 20:06:15 +08:00
parent 6302f88bf0
commit 483b131ef0
24 changed files with 1118 additions and 94 deletions
+13
View File
@@ -3195,6 +3195,19 @@ does the same in a terminal: open the link it prints, then paste the address
the browser ended on. Keys, sign-ins and plugins live in the volume, so a
restart, or a new container on the same volume, keeps them.
Magpie Browser's extension can't be loaded from the container's folders, so
in the browser UI the Library's Magpie Browser sheet offers *Download the
extension*: a zip pointed at the page's own address (3430 hands the
gateway's routes on), with a gateway key named **Magpie Browser** of its
own, made once and reused while it is on. Unzip it and choose the folder
with Load unpacked on `chrome://extensions`. An extension already loaded
takes the address and a gateway key in its popup. The browser that
connects with the page's Magpie Browser key is the container's own: its
agents use it as they would one on loopback, and so does a caller of
`/mcp/magpie/browser` from the host given that same key. A browser that
connects with another key is that key's alone. A browser connecting from
outside with no key, or from a web page's origin, is refused as before.
The image has a `HEALTHCHECK`: `magpie healthcheck` exits 0 while the gateway
answers on `MAGPIE_ADDR`, under `serve` and `web` alike, so `docker ps` shows
the container as healthy (Compose: `depends_on: condition: service_healthy`)
+1
View File
@@ -67,6 +67,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
- magpie's own MCP servers (`magpie-image`, `magpie-browser`, `magpie-web-search`, `magpie-vision`, and any `mcp …` run by a program named magpie) run this computer's magpie (#1439). `InstallServer` gives it magpie by full path (`update.Program`: the AppImage, not its mount; Homebrew's opt link, not the Cellar), and that path is right only on this computer. When the library is read, and after every change, `heal` points such a server whose program isn't on this computer (another system's path, a magpie moved out of Downloads, a bare `magpie`) at this magpie, so the agents and `CheckServers` get it; a magpie program that is here (another build) and a server run by any other program stay as they are. A carried library (`Collect`, for a backup or a WebDAV or S3 sync) names it as plain `magpie`, so two computers carry the same bundle and a sync doesn't write one's path over the other's; `Put` then reads it as that computer's magpie. [`self_here.go`](../../internal/library/self_here.go)
- Magpie Web Search (`magpie-web-search`, `searchServer` in [`market.go`](../../internal/library/market.go)) is the featured, opt-in server for magpie's web search: `magpie mcp search` (`RunSearch` in [`browsermcp.go`](../../internal/browsermcp/browsermcp.go)) passes each stdio message to the gateway's `/mcp/magpie/web-search`, as `magpie mcp browser` does to its own path, with no browser session. Its sheet says each search goes where Settings › Models › Web search sends it. That page's MCP server row (`#searchMcpRow`) keeps the address to copy, and under its words Give agents Magpie Web Search… opens the sheet in the Library (`magpie.call("library", "server", "magpie-web-search")`), Turn on the Library when the Library is off, and nothing in gateway mode, as Settings › Images does for Magpie Image (lutra_fs on Discord: the search was in Settings and not in the Library; `search-mcp-library.test.cjs`). Each agent is given a 120-second tool timeout for it (`selfTimeout`). An agent in WSL is not given it directly, as with Magpie Browser; the MCP router serves it there.
- Magpie Browser (`magpie-browser`) is opt-in, added with no agents, so the router offers it to none until one is ticked (an agent asked to use the browser reached for AppleScript instead). While its extension is connected (`GET /api/library/browser`, read again every 3 seconds while the row is shown) and no agent has it, its row in the MCP list asks which agents may use it, on a line of its own under the row's name, command and chips (from the name's left edge to the row's right one, the row's `lib-asking`), a button per agent whose chip can be clicked; a button clicks that chip, so the choice goes through `servers/agents` as a chip's does, and the row asks nothing more (`browserAsk` in [`client.js`](../../internal/gui/assets/plugins/library/client.js); `library-browser-ask.test.cjs`).
- A page whose browser can't reach magpie's folders (magpie in a container, `gateway.InContainer`, or a page from another computer) is told so (`browserJSON.Away`), and the sheet's button is Download the extension: `POST /api/library/browser/extension` with the page's origin answers a zip of the extension (`browserext.Zip`) pointed at that origin, with the secret of the On gateway key named Magpie Browser, made by the first download (`browserKey`). It is a POST so a cross-site link can't mint a key. A browser connecting from elsewhere with a key belongs to it: the gateway's relay gives it only to sessions tagged `key:<id>/` (`browserOwner`, `keyedSession` in [`browser.go`](../../internal/gateway/browser.go)), which is what a remote caller's session is forced to. The key the page makes is recorded as this magpie's own browser's (`SetOwnBrowserKey`, a file in the settings folder), and a browser connecting with it serves this computer's sessions too (`browserConn.own`, `serves`); a record that can't be read names no key (`TestBrowserIsItsKeys`; `TestOwnBrowserKeyIsThisComputers`; `TestBrowserExtensionDownload`; `library-browser-away.test.cjs`).
- Magpie Image Recognition (`magpie-vision`, `visionServer` in [`market.go`](../../internal/library/market.go)) is the featured, opt-in server for image recognition, beside Magpie Image and Magpie Web Search (matrix0487 on Discord: Discover had two of magpie's three): `magpie mcp vision` (`RunVision` in [`browsermcp.go`](../../internal/browsermcp/browsermcp.go)) passes each stdio message to the gateway's `/mcp/magpie/vision`, and makes `analyze_image`'s relative `image` path one in the agent's own folder on the way (`imageFrom`), since the gateway can't know where the agent runs; an absolute path, `~`, a URL or a drive goes as written. Its sheet says each image goes to Settings › Models › Images › Image recognition's model. That row has Give agents Magpie Image Recognition… (`libWay` in app.js, shared with Images' and Web search's links), Turn on the Library with the Library off, and nothing with recognition off or in gateway mode (`vision-mcp-library.test.cjs`). It gets the same 120-second tool timeout and the same WSL rule as Magpie Web Search.
- Discover's featured list is the same with nothing set up: one of magpie's own whose model or search isn't there yet, or which Settings turned off, carries `unready` (`gateway.OwnUnready`, set by the GUI's `/api/library/market/servers`), shown as a Not set up yet badge on its card and the full reason in its sheet. It can still be added, since it answers once that is set up, and until then its tools answer with the same reason, so no agent is given a tool that fails without a word.
- A carried library (`Collect`) has every file of each skill, its templates and other binaries included, up to `maxCarried` (16 MiB) a file and `maxCarriedAll` (32 MiB) in all, chosen smallest first across the skills (`readSkills`), so every skill's text goes before any big file. The total keeps a sealed backup under the 64 MiB a sync reads: the files are base64 twice in it. What is left out is named in `Left`, and `Put` keeps this computer's copy of such a file in the skill it puts (`keepLeft`). [`carry.go`](../../internal/library/carry.go)
+1 -1
View File
@@ -41,7 +41,7 @@ The gateway can't import the library (the library imports the gateway), so the g
- A tool turned off in the Library is neither listed nor run, for every agent, including those that have no setting of their own for it.
- A call that times out leaves the server running for the next; a server that died is started again. A server that can't be started is an error on each call, not a retry loop.
- Every process the router starts is in a `proc` tree magpie ends when the switch goes off, the server is edited, it has been idle, or the gateway stops. A test ends them in cleanup (`hubSandbox`).
- A caller from another computer (a LAN key, a tunnel or proxy here) or a web page is never given a server that acts as this computer's user (`HubServer.HereOnly`): Magpie Browser, which `/mcp/magpie/browser` refuses it directly, magpie's image server, which draws with this magpie's own token past the key's models, accounts and spend, and another magpie's router, which passes a call on to its own browser. They are neither listed nor run, in the gateway (`hubServersOf`, `hubTools`) and again in the library (`visitorServers`, `Call`) (`TestHubKeepsThisComputersOwnServersHere`, both packages). Such a caller uses `/mcp/magpie/image` directly, held to its key.
- A caller from another computer (a LAN key, a tunnel or proxy here) or a web page is never given a server that acts as this computer's user (`HubServer.HereOnly`): Magpie Browser, which `/mcp/magpie/browser` refuses it directly, magpie's image server, which draws with this magpie's own token past the key's models, accounts and spend, and another magpie's router, which passes a call on to its own browser. They are neither listed nor run, in the gateway (`hubServersOf`, `hubTools`) and again in the library (`visitorServers`, `Call`) (`TestHubKeepsThisComputersOwnServersHere`, both packages). Such a caller uses `/mcp/magpie/image` directly, held to its key. The exception is a keyed visitor's own browser: `magpie mcp browser` is `HubServer.Keyed`, given to a caller from elsewhere only when it came with a gateway key (`HubVisitor.Key`), and `hubCall` names its session `key:<id>/…`, so it reaches only a browser that connected with that same key (`TestHubGivesAKeyItsBrowser`); this computer's own browser stays here.
- A gateway key with no hold reaches the Library's other command servers through the router from another computer while it is on, as it reaches plugin tools. They run with the user's rights on this computer. A key held to some models, accounts or a spend limit (`nativeHeld`) is given only the HTTP servers elsewhere (`HubServer.Program` false), not a program run here.
- A tools plugin's server (`plugin` set, [Plugin tools](plugin-tools.md)) is behind the router as any server is, but its tools are listed and run in this process through the plugin host, not over its URL, and they aren't cached: the host has them.
- A Remote magpie's server is offered once and asked for only then; a remote whose router is turned off later keeps its server (its tools list empty). The provider's own extra headers (a proxy's) aren't carried to it, and a remote with several keys is asked with its first (`p.Key`). A server the user added at another magpie's router also sends `X-Magpie-Router`, so that router leaves out its own Remote magpies' servers for it.
+63 -16
View File
@@ -6,6 +6,7 @@
package browserext
import (
"archive/zip"
"bytes"
"embed"
"fmt"
@@ -48,25 +49,14 @@ func File(name string) ([]byte, error) { return files.ReadFile("ext/" + name) }
// A file is written only when it changed, so a browser that has the folder
// loaded sees no change it has to reload for.
func Write(dir, gatewayURL string) error {
ws := "ws" + strings.TrimPrefix(strings.TrimRight(gatewayURL, "/"), "http")
if !strings.HasPrefix(ws, "ws://") && !strings.HasPrefix(ws, "wss://") {
return fmt.Errorf("the gateway's address %q isn't http", gatewayURL)
cfg, err := config(gatewayURL, "")
if err != nil {
return err
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
return fs.WalkDir(files, "ext", func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
b, err := files.ReadFile(p)
if err != nil {
return err
}
name := strings.TrimPrefix(p, "ext/")
if name == "config.js" {
b = fmt.Appendf(nil, "// The gateway this extension talks to, written by magpie.\nexport const GATEWAY = %q;\n", ws)
}
return each(cfg, func(name string, b []byte) error {
to := filepath.Join(dir, filepath.FromSlash(name))
if old, err := os.ReadFile(to); err == nil && bytes.Equal(old, b) {
return nil
@@ -79,6 +69,63 @@ func Write(dir, gatewayURL string) error {
})
}
// Zip is the extension as a zip of its folder, pointed at the gateway at
// gatewayURL and taken there with key: for a browser on another computer
// than magpie's, or outside the container magpie runs in, where magpie
// can't write the folder.
func Zip(gatewayURL, key string) ([]byte, error) {
cfg, err := config(gatewayURL, key)
if err != nil {
return nil, err
}
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
err = each(cfg, func(name string, b []byte) error {
w, err := zw.Create(Folder + "/" + name)
if err != nil {
return err
}
_, err = w.Write(b)
return err
})
if err == nil {
err = zw.Close()
}
return buf.Bytes(), err
}
// Folder is the name of the extension's folder.
const Folder = "Magpie Browser Extension"
// config is the extension's config.js for the gateway at gatewayURL
// (http://127.0.0.1:3425) and key ("" for none, a gateway on this
// computer's loopback).
func config(gatewayURL, key string) ([]byte, error) {
ws := "ws" + strings.TrimPrefix(strings.TrimRight(gatewayURL, "/"), "http")
if !strings.HasPrefix(ws, "ws://") && !strings.HasPrefix(ws, "wss://") {
return nil, fmt.Errorf("the gateway's address %q isn't http", gatewayURL)
}
return fmt.Appendf(nil, "// The gateway this extension talks to, written by magpie.\nexport const GATEWAY = %q;\nexport const KEY = %q;\n", ws, key), nil
}
// each calls put with each of the extension's files, config.js as cfg.
func each(cfg []byte, put func(name string, b []byte) error) error {
return fs.WalkDir(files, "ext", func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
b, err := files.ReadFile(p)
if err != nil {
return err
}
name := strings.TrimPrefix(p, "ext/")
if name == "config.js" {
b = cfg
}
return put(name, b)
})
}
// Dir is where the extension is written: in the home folder, where Finder
// and Explorer show it, to drag from or choose.
func Dir() string {
@@ -86,7 +133,7 @@ func Dir() string {
if err != nil {
return OldDir()
}
return filepath.Join(home, "Magpie Browser Extension")
return filepath.Join(home, Folder)
}
// OldDir is where v0.1.2442 wrote it, a hidden folder no one could find;
+55 -1
View File
@@ -1,7 +1,10 @@
package browserext
import (
"archive/zip"
"bytes"
"encoding/json"
"io"
"os"
"path/filepath"
"strings"
@@ -17,7 +20,7 @@ func TestWritePointsAtTheGateway(t *testing.T) {
t.Fatal(err)
}
cfg, _ := os.ReadFile(filepath.Join(dir, "config.js"))
if !strings.Contains(string(cfg), `export const GATEWAY = "ws://127.0.0.1:3425";`) {
if !strings.Contains(string(cfg), `export const GATEWAY = "ws://127.0.0.1:3425";`) || !strings.Contains(string(cfg), `export const KEY = "";`) {
t.Fatalf("config.js: %s", cfg)
}
var man struct {
@@ -48,6 +51,57 @@ func TestWritePointsAtTheGateway(t *testing.T) {
}
}
// The extension's every file imports what config.js exports, so a written
// config.js has each name the source's has.
func TestConfigHasEveryExport(t *testing.T) {
src, _ := File("config.js")
cfg, err := config("http://127.0.0.1:3425", "")
if err != nil {
t.Fatal(err)
}
for _, line := range strings.Split(string(src), "\n") {
if name, ok := strings.CutPrefix(line, "export const "); ok {
name, _, _ = strings.Cut(name, " ")
if !strings.Contains(string(cfg), "export const "+name+" ") {
t.Errorf("written config.js has no %s: %s", name, cfg)
}
}
}
}
// The zip a browser outside magpie's computer or container loads holds
// the extension's folder, pointed at the address it was asked for and
// carrying the key.
func TestZipCarriesAddressAndKey(t *testing.T) {
b, err := Zip("https://magpie.example:8443", "mk-\"x")
if err != nil {
t.Fatal(err)
}
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
t.Fatal(err)
}
seen := map[string]string{}
for _, f := range zr.File {
r, _ := f.Open()
body, _ := io.ReadAll(r)
r.Close()
seen[f.Name] = string(body)
}
cfg := seen[Folder+"/config.js"]
if !strings.Contains(cfg, `export const GATEWAY = "wss://magpie.example:8443";`) || !strings.Contains(cfg, `export const KEY = "mk-\"x";`) {
t.Fatalf("config.js: %s", cfg)
}
for _, name := range []string{"manifest.json", "background.js", "popup.js"} {
if seen[Folder+"/"+name] == "" {
t.Errorf("no %s in %v", name, len(seen))
}
}
if _, err := Zip("ftp://x", "k"); err == nil {
t.Fatal("took an address that isn't http")
}
}
// An extension is told to reload only into a newer version than its own.
func TestOlder(t *testing.T) {
for _, c := range []struct {
+15 -3
View File
@@ -2,7 +2,7 @@
// calls of the agents it serves (magpie mcp browser), and it carries them
// out in this browser's own tabs, signed in to whatever the user is.
import { GATEWAY } from "./config.js";
import { GATEWAY, KEY } from "./config.js";
import { attach, fault, forget, read, send, settle, sleep, state, waitLoad, watch, watchConsole } from "./cdp.js";
import { find, take } from "./snapshot.js";
import { press as keyPress } from "./keys.js";
@@ -25,13 +25,25 @@ async function gatewayURL() {
return GATEWAY;
}
// the gateway key a magpie on another computer, or in a container, takes
// the extension with (magpie on this computer needs none): the popup's,
// else the one magpie wrote in when it gave the extension out
async function gatewayKey() {
try {
const { key } = await chrome.storage.local.get("key");
if (key !== undefined) return key;
} catch {}
return KEY || "";
}
async function connect() {
if (connecting || (ws && ws.readyState <= 1)) return;
connecting = true;
const base = await gatewayURL();
const key = await gatewayKey();
let s;
try {
s = new WebSocket(base.replace(/\/$/, "") + "/v1/magpie/browser/extension");
s = new WebSocket(base.replace(/\/$/, "") + "/v1/magpie/browser/extension" + (key ? "?key=" + encodeURIComponent(key) : ""));
} catch (e) {
connecting = false;
setStatus({ connected: false, gateway: base, error: String(e.message || e) });
@@ -83,7 +95,7 @@ chrome.alarms.onAlarm.addListener(() => connect());
chrome.runtime.onStartup.addListener(() => connect());
chrome.runtime.onInstalled.addListener(() => connect());
chrome.storage.onChanged.addListener((c, area) => {
if (area === "local" && c.gateway) {
if (area === "local" && (c.gateway || c.key)) {
retry = 1000;
if (ws) ws.close();
else connect();
+3 -1
View File
@@ -1,3 +1,5 @@
// The gateway this extension talks to. magpie writes this file when it
// writes the extension, with the address its gateway listens on.
// writes the extension, with the address its gateway listens on, and the
// gateway key it takes the extension with when it is on another computer.
export const GATEWAY = "ws://127.0.0.1:3425";
export const KEY = "";
+1 -1
View File
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "Magpie Browser",
"version": "0.1.6",
"version": "0.1.7",
"description": "Lets the agents you run through Magpie use this browser: your tabs, signed in to the sites you use.",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwjVk++2N/+l0PX53QSgXvBmDiyIOFXPDRTSo6l7HfM633QbDes2FXjS09l6hY33gsVX9eXE9O+94jQD2SVKSBn8V/EsL3f7mbNfkBqsZ4hYF3ogYxHUjJD6wjKHMFZQi54ArMZBI/psMUBbIjVTeuU9EGwnxoYU5umC8UHvEwkb4ZO0lprP3PGbHDjxrNi5fdFI8azVjyX0zlYlSw2wv0bCAZdkWuRoZWWgKdQwpdtRHrDQMnulWXT5DmNLYDpHgCreDrVaVLXzIAblSLOkZFo/T5xBiicmEbkWPbb8d3iE0OQStm1HYLdp4LLeKnnU6B7Kj/woOFt1uGIwoMqPzswIDAQAB",
"minimum_chrome_version": "116",
+2
View File
@@ -29,6 +29,8 @@
<summary>Gateway</summary>
<label for="gw">Magpie's address</label>
<input id="gw" spellcheck="false">
<label for="key" id="keyLabel">Gateway key</label>
<input id="key" type="password" spellcheck="false" autocomplete="off">
<button id="save">Save and reconnect</button>
</details>
</main>
+11 -4
View File
@@ -1,9 +1,9 @@
import { GATEWAY } from "./config.js";
import { GATEWAY, KEY } from "./config.js";
const zh = /^zh/i.test(navigator.language);
const say = zh
? { on: "已连接 Magpie", off: "未连接 Magpie", onHint: "通过 Magpie 运行的智能体可以使用这个浏览器里的标签页。它们打开的标签页放在各自的 “Magpie” 分组里。", offHint: "请确认 Magpie 正在运行。扩展会自动重连。" }
: { on: "Connected to Magpie", off: "Not connected to Magpie", onHint: "Agents you run through Magpie can use this browser's tabs. Each puts the tabs it opens in a \"Magpie\" group of its own.", offHint: "Check that Magpie is running. The extension reconnects by itself." };
? { on: "已连接 Magpie", off: "未连接 Magpie", onHint: "通过 Magpie 运行的智能体可以使用这个浏览器里的标签页。它们打开的标签页放在各自的 “Magpie” 分组里。", offHint: "请确认 Magpie 正在运行。扩展会自动重连。", key: "网关密钥", gw: "Magpie 的地址", save: "保存并重连" }
: { on: "Connected to Magpie", off: "Not connected to Magpie", onHint: "Agents you run through Magpie can use this browser's tabs. Each puts the tabs it opens in a \"Magpie\" group of its own.", offHint: "Check that Magpie is running. The extension reconnects by itself.", key: "Gateway key", gw: "Magpie's address", save: "Save and reconnect" };
async function show() {
const { status } = await chrome.storage.session.get("status");
@@ -14,11 +14,18 @@ async function show() {
}
const gw = document.getElementById("gw");
chrome.storage.local.get("gateway").then(({ gateway }) => { gw.value = gateway || GATEWAY; });
const key = document.getElementById("key");
document.querySelector('label[for="gw"]').textContent = say.gw;
document.getElementById("keyLabel").textContent = say.key;
document.getElementById("save").textContent = say.save;
chrome.storage.local.get(["gateway", "key"]).then(({ gateway, key: k }) => { gw.value = gateway || GATEWAY; key.value = k !== undefined ? k : KEY; });
document.getElementById("save").addEventListener("click", async () => {
const v = gw.value.trim();
if (!v || v === GATEWAY) await chrome.storage.local.remove("gateway");
else await chrome.storage.local.set({ gateway: v.replace(/^http/, "ws") });
const k = key.value.trim();
if (k === KEY) await chrome.storage.local.remove("key");
else await chrome.storage.local.set({ key: k });
chrome.runtime.sendMessage({ type: "reconnect" }).catch(() => {});
});
chrome.storage.onChanged.addListener((c, area) => { if (area === "session" && c.status) show(); });
+189 -42
View File
@@ -7,14 +7,17 @@ import (
"fmt"
"log"
"net/http"
"slices"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/coder/websocket"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/browserext"
"github.com/yetone/magpie/internal/settings"
)
// Magpie Browser: the agents magpie serves use the user's own browser,
@@ -24,13 +27,21 @@ import (
// working when its account changes.
//
// The extension holds a WebSocket to BrowserExtensionPath, taken only from
// its own origin on this computer. An agent calls the tools at
// BrowserMCPPath (Streamable HTTP, or `magpie mcp browser` over stdio),
// and each call is handed to the extension, which carries it out with the
// DevTools protocol in the tab and answers with MCP content. Only this
// computer's agents may: unlike the other servers of magpie's own, it is
// never served to another machine, shared or not, since it acts as the
// user wherever they are signed in.
// its own origin. An agent calls the tools at BrowserMCPPath (Streamable
// HTTP, or `magpie mcp browser` over stdio), and each call is handed to
// the extension, which carries it out with the DevTools protocol in the
// tab and answers with MCP content.
//
// Whose browser is whose: the tools act as the user wherever the browser
// is signed in, so a browser is used only by who it is the browser of.
// One on this computer (a loopback connection) is this computer's, and
// only this computer's agents use it. One elsewhere connects with a
// gateway key (magpie in a container, whose host's browser reaches it
// through a published port, or a browser on another computer), and is
// that key's: only callers with that key use it, and this computer's
// agents don't. A caller on another computer with no key, or with another
// key, is never handed a browser. Keyed callers' sessions are the key's
// own ("key:<id>/…", browserOwner), so a key names only its own browsers.
// BrowserMCPPath is where the browser MCP server is served.
const BrowserMCPPath = "/mcp/magpie/browser"
@@ -69,8 +80,15 @@ type browserConn struct {
id string // b1, b2: in the order they connected, while magpie runs
version string
agent string
since time.Time
wmu sync.Mutex
// key is the gateway key the browser connected with, whose callers
// use it; "" for this computer's, connected over loopback
key string
// own: key is the one this magpie's own page made for the user's own
// browser (OwnBrowserKey), so this computer's callers use it too, as
// they do one on loopback
own bool
since time.Time
wmu sync.Mutex
}
// browserName is the browser a User-Agent names, with its major version:
@@ -103,27 +121,107 @@ func (c *browserConn) send(ctx context.Context, v any) error {
return c.c.Write(ctx, websocket.MessageText, b)
}
func (b *browserRelay) current() *browserConn { return b.forSession("") }
// forSession is the browser a session's calls go to: the one it picked
// while that one is connected, else the last to connect.
func (b *browserRelay) forSession(session string) *browserConn {
// current is the browser connected last, whoever's it is, for the GUI.
func (b *browserRelay) current() *browserConn {
b.mu.Lock()
defer b.mu.Unlock()
if c := b.chosen[session]; c != nil && session != "" {
return c
}
if len(b.conns) == 0 {
return nil
}
return b.conns[len(b.conns)-1]
}
// all is every connected browser, the first to connect first
func (b *browserRelay) all() []*browserConn {
// browserOwner is the gateway key whose browsers a session's calls go to:
// the id in a "key:<id>/" the session starts with (after the "hub:" of a
// call through magpie's router), "" for this computer's own.
func browserOwner(session string) string {
rest, ok := strings.CutPrefix(strings.TrimPrefix(session, "hub:"), "key:")
if !ok {
return ""
}
// a session that says it is a key's but names none is no one's: never
// this computer's ("" is no key's id)
if id, _, ok := strings.Cut(rest, "/"); ok && id != "" {
return id
}
return "?"
}
// keyedSession is session as a caller with gateway key id names it: its
// own, so it reaches only that key's browsers whatever it says.
func keyedSession(id, session string) string { return "key:" + id + "/" + session }
// serves: a session owned by owner (browserOwner) may use c. This
// computer's callers ("") use this computer's browsers and the one its
// own page gave a key (own); a key's callers use the browsers that
// connected with that key.
func (c *browserConn) serves(owner string) bool {
if owner == "" {
return c.key == "" || c.own
}
return c.key == owner
}
// ownBrowserKeyFile holds the id of the gateway key this magpie's page
// made for the user's own browser, when magpie's folders are out of that
// browser's reach (magpie in a container, the page on another computer):
// the extension downloaded from the page connects with it.
func ownBrowserKeyFile() string { return filepath.Join(settings.Dir(), "browser-key") }
// OwnBrowserKey is the id SetOwnBrowserKey recorded; "" when there is
// none or it can't be read, and a browser with a key is then only that
// key's.
func OwnBrowserKey() string {
b, err := os.ReadFile(ownBrowserKeyFile())
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
// SetOwnBrowserKey records id as the gateway key of the user's own
// browser (OwnBrowserKey).
func SetOwnBrowserKey(id string) error {
if err := os.MkdirAll(settings.Dir(), 0o700); err != nil {
return err
}
tmp := ownBrowserKeyFile() + ".tmp"
if err := os.WriteFile(tmp, []byte(id+"\n"), 0o600); err != nil {
return err
}
return os.Rename(tmp, ownBrowserKeyFile())
}
// forSession is the browser a session's calls go to: the one it picked
// while that one is connected, else the last of its owner's to connect.
func (b *browserRelay) forSession(session string) *browserConn {
b.mu.Lock()
defer b.mu.Unlock()
return slices.Clone(b.conns)
owner := browserOwner(session)
if c := b.chosen[session]; c != nil && session != "" && c.serves(owner) {
return c
}
for i := len(b.conns) - 1; i >= 0; i-- {
if b.conns[i].serves(owner) {
return b.conns[i]
}
}
return nil
}
// all is every browser session's calls may go to, the first to connect
// first
func (b *browserRelay) all(session string) []*browserConn {
b.mu.Lock()
defer b.mu.Unlock()
owner := browserOwner(session)
var out []*browserConn
for _, c := range b.conns {
if c.serves(owner) {
out = append(out, c)
}
}
return out
}
// choose has a session's calls go to the connected browser named by its id
@@ -133,8 +231,13 @@ func (b *browserRelay) choose(session, which string) (*browserConn, error) {
which = strings.ToLower(strings.TrimSpace(which))
b.mu.Lock()
defer b.mu.Unlock()
var by []*browserConn
owner := browserOwner(session)
var by, theirs []*browserConn
for _, c := range b.conns {
if !c.serves(owner) {
continue
}
theirs = append(theirs, c)
if c.id == which {
by = []*browserConn{c}
break
@@ -144,8 +247,8 @@ func (b *browserRelay) choose(session, which string) (*browserConn, error) {
}
}
switch {
case len(b.conns) == 0:
return nil, errBrowserAway
case len(theirs) == 0:
return nil, browserAway(session)
case len(by) == 0:
return nil, fmt.Errorf("no connected browser is %q: browser_tabs with action browsers lists them", which)
case len(by) > 1:
@@ -196,7 +299,7 @@ func (b *browserRelay) answered(id string, result json.RawMessage) {
func (b *browserRelay) call(ctx context.Context, session, tool string, args json.RawMessage) (json.RawMessage, error) {
c := b.forSession(session)
if c == nil {
return nil, errBrowserAway
return nil, browserAway(session)
}
b.mu.Lock()
if b.pending == nil {
@@ -232,10 +335,42 @@ func (b *browserRelay) call(ctx context.Context, session, tool string, args json
var errBrowserAway = errors.New("Magpie Browser isn't connected, so there is no browser to use. Ask the user to set it up: magpie's Library → Magpie Browser → Set up, which loads the extension in Chrome, Edge or another Chromium browser. Once installed it connects by itself whenever that browser and magpie are both running.")
// browserAway is why session has no browser to use.
func browserAway(session string) error {
if browserOwner(session) == "" {
return errBrowserAway
}
return errors.New("Magpie Browser isn't connected with this gateway key, so there is no browser to use: a browser connects as a key's when its extension is given the key (the extension's popup → Gateway key), and is used only by that key's agents and magpie's own. Ask the user to set it up there.")
}
// browserExtensionKey is the gateway key the extension's request r comes
// with ("" for one on this computer), and whether it is let connect: from
// this computer over loopback, or with a gateway key that is on.
func browserExtensionKey(r *http.Request) (string, bool) {
if r.Header.Get("Origin") != browserext.Origin {
return "", false
}
if local(r) && loopbackHost(r.Host) {
return "", true
}
if id := access.Caller(r.Context()).KeyID; id != "" {
return id, true
}
// a key lanGuard didn't read: the gateway isn't on the network, so
// this is a container's published port or a proxy on this computer
for _, k := range callerKeys(r) {
if c, ok := access.Authenticate(k); ok && c.KeyID != "" {
return c.KeyID, true
}
}
return "", false
}
// browserExtension takes the extension's WebSocket.
func (s *Server) browserExtension(w http.ResponseWriter, r *http.Request) {
if !local(r) || !loopbackHost(r.Host) || r.Header.Get("Origin") != browserext.Origin {
http.Error(w, "only the Magpie Browser extension, on this computer, connects here", http.StatusForbidden)
key, ok := browserExtensionKey(r)
if !ok {
http.Error(w, "only the Magpie Browser extension connects here: on this computer, or with a gateway key", http.StatusForbidden)
return
}
ws, err := websocket.Accept(w, r, &websocket.AcceptOptions{OriginPatterns: []string{"chrome-extension://" + browserext.ID}})
@@ -244,7 +379,7 @@ func (s *Server) browserExtension(w http.ResponseWriter, r *http.Request) {
return
}
ws.SetReadLimit(64 << 20) // a full-page screenshot
c := &browserConn{c: ws, since: time.Now()}
c := &browserConn{c: ws, key: key, own: key != "" && key == OwnBrowserKey(), since: time.Now()}
ctx := r.Context()
defer ws.CloseNow()
added := false
@@ -275,7 +410,11 @@ func (s *Server) browserExtension(w http.ResponseWriter, r *http.Request) {
if !added {
s.browser.add(c)
added = true
log.Printf("Magpie Browser %s connected", m.Version)
if key != "" {
log.Printf("Magpie Browser %s connected with gateway key %s", m.Version, key)
} else {
log.Printf("Magpie Browser %s connected", m.Version)
}
}
if browserext.Older(m.Version, browserext.Version()) {
// an older extension: its folder gets this magpie's, which
@@ -311,11 +450,10 @@ func (s *Server) browserStatus(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) browserMCP(w http.ResponseWriter, r *http.Request) {
// never another machine's, a gateway key or not: the tools act as the
// user wherever their browser is signed in; and no web page's, whatever
// Settings lists
if !local(r) || fromBrowser(r) {
http.Error(w, "magpie's browser MCP server answers agents on this computer only", http.StatusForbidden)
// no web page's, whatever Settings lists; another computer's only with
// a gateway key, and then only that key's browsers (browserSession)
if fromBrowser(r) || (!local(r) && access.Caller(r.Context()).KeyID == "") {
http.Error(w, "magpie's browser MCP server answers agents on this computer, or with a gateway key", http.StatusForbidden)
return
}
serveMCP(w, r, "magpie's browser", "magpie-browser", 1<<20, s.browserMCPCall)
@@ -388,7 +526,7 @@ func (s *Server) browserMCPCall(r *http.Request, m mcpMessage) (any, map[string]
}
// with two browsers connected, the list of tabs says whose they are
if p.Name == "browser_tabs" && (tabs.Action == "" || tabs.Action == "list") {
if all := s.browser.all(); len(all) > 1 {
if all := s.browser.all(session); len(all) > 1 {
if c := s.browser.forSession(session); c != nil {
if content, ok := result["content"].([]any); ok {
result["content"] = append([]any{map[string]any{"type": "text", "text": fmt.Sprintf("These are %s's tabs (%s); %d browsers are connected: browser_tabs with action browsers lists them.", c.id, c.name(), len(all))}}, content...)
@@ -454,9 +592,9 @@ func (s *Server) browserShot(result map[string]any, data, why string) {
// list is the connected browsers, the one session's calls go to marked *.
func (b *browserRelay) list(session string) string {
all := b.all()
all := b.all(session)
if len(all) == 0 {
return errBrowserAway.Error()
return browserAway(session).Error()
}
mine := b.forSession(session)
lines := []string{fmt.Sprintf("%d browsers with Magpie Browser are connected (* is the one calls go to; browser_tabs with action use and browser picks another, by id or name):", len(all))}
@@ -471,15 +609,24 @@ func (b *browserRelay) list(session string) string {
}
// browserSession is which agent session a call is from: the header the
// stdio server sends, else the MCP session, else the agent.
// stdio server sends, else the MCP session, else the agent. Another
// computer's caller's is its gateway key's (keyedSession); this
// computer's callers are trusted with any.
func browserSession(r *http.Request) string {
session := "default"
for _, h := range []string{BrowserSessionHeader, "Mcp-Session-Id"} {
if v := boundedSession(r.Header.Get(h)); v != "" {
return v
session = v
break
}
}
if a := callerOf(r).agent; a != "" {
return "agent:" + a
if session == "default" {
if a := callerOf(r).agent; a != "" {
session = "agent:" + a
}
}
return "default"
if !local(r) {
return keyedSession(access.Caller(r.Context()).KeyID, session)
}
return session
}
+254 -16
View File
@@ -6,6 +6,8 @@ import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"time"
@@ -37,10 +39,24 @@ func fakeExtension(t *testing.T, base string, answer func(id, session, tool stri
// fakeExtensionAs is fakeExtension in the browser whose User-Agent is agent.
func fakeExtensionAs(t *testing.T, base, agent string, answer func(id, session, tool string, args map[string]any) any) {
t.Helper()
fakeExtensionWith(t, base, "", nil, agent, answer)
}
// fakeExtensionWith is fakeExtensionAs given key (as the extension's popup
// is) and sending hdr.
func fakeExtensionWith(t *testing.T, base, key string, hdr http.Header, agent string, answer func(id, session, tool string, args map[string]any) any) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
c, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(base, "http")+BrowserExtensionPath,
&websocket.DialOptions{HTTPHeader: http.Header{"Origin": {browserext.Origin}}})
h := http.Header{"Origin": {browserext.Origin}}
for k, v := range hdr {
h[k] = v
}
u := "ws" + strings.TrimPrefix(base, "http") + BrowserExtensionPath
if key != "" {
u += "?key=" + url.QueryEscape(key)
}
c, _, err := websocket.Dial(ctx, u, &websocket.DialOptions{HTTPHeader: h})
if err != nil {
cancel()
t.Fatal(err)
@@ -171,9 +187,14 @@ func TestBrowserMCPGuarded(t *testing.T) {
t.Fatalf("not shared: %d %s", w.Code, w.Body.String())
}
_, secrets := newCaller(t, "Laptop")
if w := browserPost(h, there, list, "Authorization", "Bearer "+secrets[0]); w.Code != http.StatusForbidden {
// with a key it is answered, and its calls go to that key's browsers
// only (TestBrowserIsItsKeys), of which there are none
if w := browserPost(h, there, list, "Authorization", "Bearer "+secrets[0]); w.Code != http.StatusOK {
t.Fatalf("shared, with a key: %d %s", w.Code, w.Body.String())
}
if w := browserPost(h, there, list, "Authorization", "Bearer mk-not-a-key"); w.Code/100 == 2 {
t.Fatalf("shared, with a wrong key: %d %s", w.Code, w.Body.String())
}
if w := browserPost(h, "127.0.0.1:5000", list, "Origin", "http://localhost:5173"); w.Code != http.StatusForbidden {
t.Fatalf("a page on this computer: %d %s", w.Code, w.Body.String())
}
@@ -193,23 +214,32 @@ func TestBrowserMCPGuarded(t *testing.T) {
}
}
// Only the extension itself, on this computer, may be the browser: a page
// that connects in its place would be handed every call, and could answer
// them.
// Only the extension itself may be the browser, on this computer or with
// a gateway key: a page that connects in its place would be handed every
// call, and could answer them.
func TestBrowserExtensionOnlyFromItsOrigin(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
h := lanGuard(New().Handler())
newCaller(t, "Laptop")
for _, c := range []struct{ addr, host, origin string }{
{"127.0.0.1:5000", "127.0.0.1:3425", "chrome-extension://abcdefghijklmnopabcdefghijklmnop"},
{"127.0.0.1:5000", "127.0.0.1:3425", "http://localhost:5173"},
{"127.0.0.1:5000", "127.0.0.1:3425", "null"},
{"127.0.0.1:5000", "127.0.0.1:3425", ""},
{"127.0.0.1:5000", "rebound.example:3425", browserext.Origin}, // DNS rebinding
{"192.0.2.7:4000", "192.0.2.1:3425", browserext.Origin}, // another computer
_, secrets := newCaller(t, "Laptop")
for _, c := range []struct{ addr, host, origin, key string }{
{"127.0.0.1:5000", "127.0.0.1:3425", "chrome-extension://abcdefghijklmnopabcdefghijklmnop", ""},
{"127.0.0.1:5000", "127.0.0.1:3425", "http://localhost:5173", ""},
{"127.0.0.1:5000", "127.0.0.1:3425", "null", ""},
{"127.0.0.1:5000", "127.0.0.1:3425", "", ""},
{"127.0.0.1:5000", "rebound.example:3425", browserext.Origin, ""}, // DNS rebinding
{"192.0.2.7:4000", "192.0.2.1:3425", browserext.Origin, ""}, // another computer, no key
{"192.0.2.7:4000", "192.0.2.1:3425", browserext.Origin, "mk-not-a-key"},
// a key is no use to a page
{"192.0.2.7:4000", "192.0.2.1:3425", "http://192.0.2.1:3425", secrets[0]},
{"192.0.2.7:4000", "192.0.2.1:3425", "chrome-extension://abcdefghijklmnopabcdefghijklmnop", secrets[0]},
{"127.0.0.1:5000", "rebound.example:3425", "http://rebound.example:3425", secrets[0]},
} {
r := httptest.NewRequest(http.MethodGet, BrowserExtensionPath, nil)
target := BrowserExtensionPath
if c.key != "" {
target += "?key=" + c.key
}
r := httptest.NewRequest(http.MethodGet, target, nil)
r.RemoteAddr, r.Host = c.addr, c.host
r.Header.Set("Connection", "Upgrade")
r.Header.Set("Upgrade", "websocket")
@@ -261,7 +291,7 @@ func TestBrowserMCPPicksAmongBrowsers(t *testing.T) {
fakeExtensionAs(t, srv.URL, chrome, in("chrome"))
browserConnected(t, s)
fakeExtensionAs(t, srv.URL, chrome+" Edg/141.0.3537.57", in("edge"))
for deadline := time.Now().Add(10 * time.Second); len(s.browser.all()) < 2; time.Sleep(5 * time.Millisecond) {
for deadline := time.Now().Add(10 * time.Second); len(s.browser.all("")) < 2; time.Sleep(5 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatal("the second extension never connected")
}
@@ -311,3 +341,211 @@ func TestBrowserName(t *testing.T) {
}
}
}
// A browser elsewhere connects with a gateway key, as one outside magpie's
// container does through its published port, and is that key's: only that
// key's callers reach it, never this computer's or another key's, and a
// key's caller never reaches this computer's browser, whatever session it
// names.
func TestBrowserIsItsKeys(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Setenv("MAGPIE_TRUST_PROXY", "")
s := New()
// a request carrying testPeer comes from that address, as the host's
// browser's does to a container (the bridge's 172.17.0.1, say)
const testPeer = "X-Test-Peer"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if p := r.Header.Get(testPeer); p != "" {
r.RemoteAddr, r.Host = p, "192.0.2.1:3425"
r.Header.Del(testPeer)
}
lanGuard(s.Handler()).ServeHTTP(w, r)
}))
t.Cleanup(srv.Close)
keys, secrets := newCaller(t, "Host browser", "Other")
const there = "172.17.0.1:40000"
sessions := make(chan string, 16)
in := func(name string) func(_, session, _ string, _ map[string]any) any {
return func(_, session, _ string, _ map[string]any) any {
sessions <- session
return map[string]any{"content": []any{map[string]any{"type": "text", "text": "tabs of " + name}}}
}
}
away := http.Header{testPeer: {there}}
// no key, or one that isn't on, from there: never connected
for _, key := range []string{"", "mk-not-a-key"} {
u := "ws" + strings.TrimPrefix(srv.URL, "http") + BrowserExtensionPath + "?key=" + key
if c, resp, err := websocket.Dial(context.Background(), u, &websocket.DialOptions{HTTPHeader: http.Header{"Origin": {browserext.Origin}, testPeer: {there}}}); err == nil {
c.CloseNow()
t.Fatalf("connected from there with key %q", key)
} else if resp == nil || resp.StatusCode/100 != 4 {
t.Fatalf("key %q: %v %v", key, resp, err)
}
}
fakeExtension(t, srv.URL, in("here"))
browserConnected(t, s)
fakeExtensionWith(t, srv.URL, secrets[0], away, "Chrome/141", in("the key's"))
for deadline := time.Now().Add(10 * time.Second); len(s.browser.all(keyedSession(keys[0].ID, "x"))) < 1; time.Sleep(5 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatal("the keyed extension never connected")
}
}
h := lanGuard(s.Handler())
tabs := func(addr string, args map[string]any, hdr ...string) (string, bool) {
t.Helper()
m := readImageReply(t, browserPost(h, addr, imageToolCall("browser_tabs", args), hdr...))
var all []string
for _, c := range m.Result.Content {
all = append(all, c.Text)
}
return strings.Join(all, "\n"), m.Result.IsError
}
mine := []string{"Authorization", "Bearer " + secrets[0], BrowserSessionHeader, "s1"}
if got, bad := tabs(there, map[string]any{}, mine...); bad || got != "tabs of the key's" {
t.Fatalf("the key's caller: %q", got)
}
if got := <-sessions; got != "key:"+keys[0].ID+"/s1" {
t.Fatalf("the key's browser was handed session %q", got)
}
// naming this computer's session, or another key's, it still has its own
for _, named := range []string{"hub:x", "key:" + keys[1].ID + "/s1", "key:/s1", "default"} {
if got, bad := tabs(there, map[string]any{}, "Authorization", "Bearer "+secrets[0], BrowserSessionHeader, named); bad || got != "tabs of the key's" {
t.Fatalf("the key's caller as %q: %q", named, got)
}
<-sessions
}
if got, _ := tabs(there, map[string]any{"action": "browsers"}, mine...); strings.Contains(got, "b1 ") || !strings.Contains(got, "b2 Chrome 141") {
t.Fatalf("the key's caller is told of %q", got)
}
if got, bad := tabs(there, map[string]any{"action": "use", "browser": "b1"}, mine...); !bad || !strings.Contains(got, `no connected browser is "b1"`) {
t.Fatalf("the key's caller picked this computer's browser: %q", got)
}
if got, bad := tabs(there, map[string]any{}, "Authorization", "Bearer "+secrets[1]); !bad || !strings.Contains(got, "isn't connected with this gateway key") {
t.Fatalf("another key's caller: %q", got)
}
if got, bad := tabs("127.0.0.1:5000", map[string]any{}, BrowserSessionHeader, "s1"); bad || got != "tabs of here" {
t.Fatalf("this computer's caller: %q", got)
}
<-sessions
if got, _ := tabs("127.0.0.1:5000", map[string]any{"action": "use", "browser": "b2"}, BrowserSessionHeader, "s1"); !strings.Contains(got, `no connected browser is "b2"`) {
t.Fatalf("this computer's caller picked the key's browser: %q", got)
}
// magpie's router runs `magpie mcp browser` here, which names its
// keyed caller's session as the router gave it (hubCall)
if got, bad := tabs("127.0.0.1:5000", map[string]any{}, BrowserSessionHeader, "hub:"+keyedSession(keys[0].ID, "c1")); bad || got != "tabs of the key's" {
t.Fatalf("the router's keyed caller: %q", got)
}
<-sessions
// the GUI's status, this computer's only, says one is connected
if s.browser.current() == nil {
t.Fatal("no browser for the GUI")
}
}
func TestBrowserOwner(t *testing.T) {
for in, want := range map[string]string{
"s1": "", "default": "", "agent:claude": "", "hub:hub-claude-x": "",
"key:k1/s1": "k1", "hub:key:k1/c": "k1", "key:k1/hub:key:k2/x": "k1",
"key:/s1": "?", "key:k1": "?", "hub:key:": "?",
} {
if got := browserOwner(in); got != want {
t.Errorf("browserOwner(%q) = %q, want %q", in, got, want)
}
}
}
// The browser connected with the key magpie's own page made for it
// (OwnBrowserKey) is this computer's too, as magpie in a container has no
// browser on loopback; one connected with another key isn't.
func TestOwnBrowserKeyIsThisComputers(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Setenv("MAGPIE_TRUST_PROXY", "")
if OwnBrowserKey() != "" {
t.Fatal("an own browser key with none recorded")
}
s := New()
const testPeer = "X-Test-Peer"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if p := r.Header.Get(testPeer); p != "" {
r.RemoteAddr, r.Host = p, "192.0.2.1:3425"
r.Header.Del(testPeer)
}
lanGuard(s.Handler()).ServeHTTP(w, r)
}))
t.Cleanup(srv.Close)
keys, secrets := newCaller(t, "Magpie Browser", "Other")
if err := SetOwnBrowserKey(keys[0].ID); err != nil {
t.Fatal(err)
}
if got := OwnBrowserKey(); got != keys[0].ID {
t.Fatalf("OwnBrowserKey = %q, want %q", got, keys[0].ID)
}
away := http.Header{testPeer: {"172.17.0.1:40000"}}
reply := func(name string) func(_, _, _ string, _ map[string]any) any {
return func(_, _, _ string, _ map[string]any) any {
return map[string]any{"content": []any{map[string]any{"type": "text", "text": "tabs of " + name}}}
}
}
h := lanGuard(s.Handler())
tabs := func(addr string, hdr ...string) (string, bool) {
t.Helper()
m := readImageReply(t, browserPost(h, addr, imageToolCall("browser_tabs", map[string]any{}), hdr...))
var all []string
for _, c := range m.Result.Content {
all = append(all, c.Text)
}
return strings.Join(all, "\n"), m.Result.IsError
}
connected := func(id string) {
t.Helper()
for deadline := time.Now().Add(10 * time.Second); len(s.browser.all(keyedSession(id, "x"))) < 1; time.Sleep(5 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatal("the extension never connected")
}
}
}
// another key's browser alone: not this computer's
fakeExtensionWith(t, srv.URL, secrets[1], away, "Chrome/141", reply("the other key's"))
connected(keys[1].ID)
if got, bad := tabs("127.0.0.1:5000", BrowserSessionHeader, "s1"); !bad || got == "tabs of the other key's" {
t.Fatalf("this computer's caller used another key's browser: %q", got)
}
fakeExtensionWith(t, srv.URL, secrets[0], away, "Chrome/141", reply("own"))
connected(keys[0].ID)
if got, bad := tabs("127.0.0.1:5000", BrowserSessionHeader, "s1"); bad || got != "tabs of own" {
t.Fatalf("this computer's caller: %q", got)
}
if got, bad := tabs("172.17.0.1:40000", "Authorization", "Bearer "+secrets[0], BrowserSessionHeader, "s1"); bad || got != "tabs of own" {
t.Fatalf("the own key's caller: %q", got)
}
if got, bad := tabs("172.17.0.1:40000", "Authorization", "Bearer "+secrets[1], BrowserSessionHeader, "s1"); bad || got != "tabs of the other key's" {
t.Fatalf("the other key's caller: %q", got)
}
}
// A record that can't be read names no key, so no keyed browser is this
// computer's.
func TestOwnBrowserKeyUnreadable(t *testing.T) {
fresh(t)
if err := os.MkdirAll(ownBrowserKeyFile(), 0o700); err != nil { // a folder in its place
t.Fatal(err)
}
if got := OwnBrowserKey(); got != "" {
t.Fatalf("OwnBrowserKey from an unreadable record = %q", got)
}
c := &browserConn{key: "k1"}
if c.serves("") {
t.Fatal("a keyed browser not own serves this computer")
}
c.own = true
if !c.serves("") || !c.serves("k1") || c.serves("k2") || c.serves("?") {
t.Fatal("an own browser serves the wrong owners")
}
if (&browserConn{}).serves("?") || (&browserConn{}).serves("k1") {
t.Fatal("this computer's browser serves a key")
}
}
+25 -4
View File
@@ -139,27 +139,40 @@ type HubServer struct {
// browser is signed in to), magpie's image server (it draws with this
// magpie's own token, past a gateway key's models, accounts and
// spend), and another magpie's router (which passes a call on to its
// own). It is given only to a caller on this computer (HubVisitor).
// own). It is given only to a caller on this computer (HubVisitor),
// Magpie Browser also to a keyed one elsewhere (Keyed).
HereOnly bool
// Program: the server is a program run on this computer, with the
// user's rights (a command, or a tools plugin), not an HTTP server
// elsewhere. A gateway key held to some models, accounts or a spend
// limit isn't given it from another computer.
Program bool
// Keyed: the server is Magpie Browser, whose browsers are each this
// computer's or a gateway key's (browser.go): given to this computer
// and to another computer's caller with a key, and calls go to that
// key's browsers only.
Keyed bool
}
// HubVisitor is who a hub request is from, for what it is given of the
// servers behind it (HubServer's HereOnly and Program): Away, another
// computer, a tunnel or a web page; Held, by a gateway key held to some
// models, accounts or a spend limit. A caller on this computer is given
// every server.
type HubVisitor struct{ Away, Held bool }
// every server. Key is the gateway key an Away visitor came with, whose
// browsers it is given (HubServer's Keyed).
type HubVisitor struct {
Away, Held bool
Key string
}
// Gives is whether v is given s.
func (v HubVisitor) Gives(s HubServer) bool {
if !v.Away {
return true
}
if s.Keyed {
return v.Key != ""
}
return !s.HereOnly && !(v.Held && s.Program)
}
@@ -180,7 +193,11 @@ func HubVisitorOf(ctx context.Context) HubVisitor {
// hubVisitor is who r is from (HubVisitor).
func hubVisitor(r *http.Request) HubVisitor {
away := !local(r) || fromBrowser(r)
return HubVisitor{Away: away, Held: away && nativeHeld(access.Caller(r.Context()))}
v := HubVisitor{Away: away, Held: away && nativeHeld(access.Caller(r.Context()))}
if !local(r) && !fromBrowser(r) {
v.Key = access.Caller(r.Context()).KeyID
}
return v
}
// RouterHeader marks a request of magpie's own router to another magpie's
@@ -665,6 +682,10 @@ func hubToolNamed(ctx context.Context, ts []hubTool, agent, name string) (hubToo
// reads them, its workspaces and client (HubCaller).
func (s *Server) hubCall(r *http.Request, agent string, t hubTool, args json.RawMessage, meta hubCallMeta) any {
c := HubCaller{Session: hubSession(r, agent, meta)}
if v := hubVisitor(r); v.Away && v.Key != "" {
// its browser is its key's, whatever session it names (browser.go)
c.Session = keyedSession(v.Key, c.Session)
}
if t.Roots {
c.Roots, c.Client = hubRoots(r, meta), hubClient(r)
}
+59
View File
@@ -1,8 +1,12 @@
package gateway
import (
"context"
"encoding/json"
"net/http"
"slices"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/access"
@@ -86,3 +90,58 @@ func TestHubKeepsThisComputersOwnServersHere(t *testing.T) {
t.Fatalf("shell for the full key: %+v", m)
}
}
// Magpie Browser is given to a keyed caller from elsewhere too, and its
// call goes under the key's session (browser.go), whatever session the
// caller names; never to one from elsewhere with no key, nor to a page.
func TestHubGivesAKeyItsBrowser(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Setenv("MAGPIE_TRUST_PROXY", "")
servers := []HubServer{{Name: "magpie-browser", HereOnly: true, Program: true, Keyed: true}}
f := &fakeHub{on: true, tools: map[string][]HubTool{"": {{Server: "magpie-browser", Tool: "do", Spec: hubSpec("do")}}}, servers: map[string][]HubServer{"": servers}}
var mu sync.Mutex
var seen []string
f.call = func(ctx context.Context, server, tool string) (json.RawMessage, error) {
mu.Lock()
seen = append(seen, HubCallerOf(ctx).Session)
mu.Unlock()
return json.RawMessage(`{"content":[{"type":"text","text":"ok"}]}`), nil
}
withHub(t, f)
h := lanGuard(New().Handler())
keys, secrets := newCaller(t, "Host", "Narrow")
if _, err := access.Update("models-key", access.Change{Key: keys[1].ID, Models: []string{"some/model"}}); err != nil {
t.Fatal(err)
}
const there = "192.0.2.7:4000"
call := toolsCall("magpie-browser"+hubSep+"do", `{}`)
for i, auth := range [][]string{{"Authorization", "Bearer " + secrets[0], "Mcp-Session-Id", "abc"}, {"Authorization", "Bearer " + secrets[1]}} {
m := readMCP(t, hubPostAt(h, HubMCPAll, there, call, auth...))
if m.Error != nil || m.Result.IsError {
t.Fatalf("key %d from there: %+v", i, m)
}
}
if w := hubPostAt(h, HubMCPAll, here, call, "Origin", "http://localhost:5173"); w.Code != http.StatusForbidden {
t.Fatalf("a page here: %d %s", w.Code, w.Body.String())
}
m := readMCP(t, hubPostAt(h, HubMCPAll, here, call, "Mcp-Session-Id", "abc"))
if m.Error != nil || m.Result.IsError {
t.Fatalf("here: %+v", m)
}
mu.Lock()
defer mu.Unlock()
want := []string{"key:" + keys[0].ID + "/hub--abc", "key:" + keys[1].ID + "/", "hub--abc"}
if !slices.Equal(seen, want) {
t.Fatalf("sessions %q, want %q", seen, want)
}
for _, v := range []HubVisitor{{Away: true}, {Away: true, Held: true}} {
if v.Gives(servers[0]) {
t.Errorf("%+v is given Magpie Browser", v)
}
}
if (HubVisitor{Away: true, Key: "k"}).Gives(HubServer{Name: "magpie-image", HereOnly: true}) {
t.Error("a key from elsewhere is given magpie's image server")
}
}
+38 -3
View File
@@ -6446,21 +6446,56 @@ magpie.plugin("library", (ctx) => {
const box = el("div", "mk-browser");
const state = el("div", "mk-browser-state");
const steps = el("ol", "mk-browser-steps");
let away = false;
const go = button(t("Set up the extension…"), "action", async () => {
go.disabled = true;
try {
draw(await api("library/browser/setup", {}));
steps.hidden = false;
if (away) await download();
else {
draw(await api("library/browser/setup", {}));
steps.hidden = false;
}
} catch (e) { status(e.message, "err"); }
go.disabled = false;
});
// magpie's folders are out of this browser's reach (another computer,
// or magpie in a container): the extension comes as a zip, pointed at
// this page's address with a gateway key of its own
const download = async () => {
const r = await fetch("/api/library/browser/extension", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ at: location.origin }),
});
if (!r.ok) throw new Error((await r.text()).trim() || r.statusText);
const url = URL.createObjectURL(await r.blob());
const a = el("a");
a.href = url;
a.download = "Magpie Browser Extension.zip";
a.click();
setTimeout(() => URL.revokeObjectURL(url), 60000);
steps.hidden = false;
};
const draw = (b) => {
away = !!b.away;
state.replaceChildren();
const dot = el("span", "mk-browser-dot" + (b.connected ? " on" : ""));
state.append(dot, el("span", "", b.connected
? t("Connected to your browser") + (b.extension ? " · " + b.extension : "")
: away ? t("Not connected: download the extension and load it in your browser")
: b.written ? t("Not connected: load the folder below in your browser, and keep that browser open") : t("Not set up: set up the extension in Chrome, Edge, Arc, Brave or another Chromium browser")));
go.textContent = b.written ? t("Show the extension folder") : t("Set up the extension…");
go.textContent = away ? t("Download the extension") : b.written ? t("Show the extension folder") : t("Set up the extension…");
if (away) {
steps.replaceChildren(
el("li", "", t("Unzip the download.")),
el("li", "", t("Open chrome://extensions (edge://extensions in Edge) in the browser you use every day.")),
el("li", "", t("Turn on Developer mode.")),
el("li", "", t("Click Load unpacked and choose the unzipped Magpie Browser Extension folder.")),
);
folder.hidden = true;
if (b.connected) steps.hidden = true;
return;
}
steps.replaceChildren(
el("li", "", t("Open chrome://extensions (edge://extensions in Edge) in the browser you use every day.")),
el("li", "", t("Turn on Developer mode.")),
@@ -169,6 +169,10 @@ magpie.strings({
"Not set up: set up the extension in Chrome, Edge, Arc, Brave or another Chromium browser": "未安装:在 Chrome、Edge、Arc、Brave 或其他 Chromium 浏览器里安装扩展",
"Open chrome://extensions (edge://extensions in Edge) in the browser you use every day.": "在你日常使用的浏览器里打开 chrome://extensions(Edge 为 edge://extensions)。",
"Turn on Developer mode.": "打开「开发者模式」。",
"Not connected: download the extension and load it in your browser": "未连接:下载扩展,并在浏览器里加载",
"Download the extension": "下载扩展",
"Unzip the download.": "解压下载的文件。",
"Click Load unpacked and choose the unzipped Magpie Browser Extension folder.": "点击「加载已解压的扩展程序」,选择解压出的 Magpie Browser Extension 文件夹。",
"Drag the folder below onto that page.": "把下面的文件夹拖到那个页面上。",
"Drag the folder from the window that opened onto that page, or click Load unpacked and choose {dir}.": "把弹出窗口里的文件夹拖到那个页面上,或点击「加载已解压的扩展程序」,选择 {dir}。",
"Drag onto chrome://extensions": "拖到 chrome://extensions 上",
@@ -959,6 +963,10 @@ magpie.strings({
"Not set up: set up the extension in Chrome, Edge, Arc, Brave or another Chromium browser": "未安裝:在 Chrome、Edge、Arc、Brave 或其他 Chromium 瀏覽器裡安裝擴充功能",
"Open chrome://extensions (edge://extensions in Edge) in the browser you use every day.": "在你日常使用的瀏覽器裡打開 chrome://extensions(Edge 為 edge://extensions)。",
"Turn on Developer mode.": "開啟「開發人員模式」。",
"Not connected: download the extension and load it in your browser": "未連線:下載擴充功能,並在瀏覽器裡載入",
"Download the extension": "下載擴充功能",
"Unzip the download.": "解壓縮下載的檔案。",
"Click Load unpacked and choose the unzipped Magpie Browser Extension folder.": "點選「載入未封裝項目」,選擇解壓縮出的 Magpie Browser Extension 資料夾。",
"Drag the folder below onto that page.": "把下面的資料夾拖到那個頁面上。",
"Drag the folder from the window that opened onto that page, or click Load unpacked and choose {dir}.": "把彈出視窗裡的資料夾拖到那個頁面上,或點擊「載入未封裝項目」,選擇 {dir}。",
"Drag onto chrome://extensions": "拖到 chrome://extensions 上",
@@ -1744,6 +1752,10 @@ magpie.strings({
"Not set up: set up the extension in Chrome, Edge, Arc, Brave or another Chromium browser": "未設定:Chrome、Edge、Arc、Brave などの Chromium ブラウザに拡張機能を設定してください",
"Open chrome://extensions (edge://extensions in Edge) in the browser you use every day.": "普段使っているブラウザで chrome://extensions(Edge では edge://extensions)を開きます。",
"Turn on Developer mode.": "デベロッパー モードをオンにします。",
"Not connected: download the extension and load it in your browser": "未接続:拡張機能をダウンロードし、ブラウザで読み込んでください",
"Download the extension": "拡張機能をダウンロード",
"Unzip the download.": "ダウンロードしたファイルを展開します。",
"Click Load unpacked and choose the unzipped Magpie Browser Extension folder.": "「パッケージ化されていない拡張機能を読み込む」をクリックし、展開した Magpie Browser Extension フォルダを選びます。",
"Drag the folder below onto that page.": "下のフォルダをそのページにドラッグします。",
"Drag the folder from the window that opened onto that page, or click Load unpacked and choose {dir}.": "開いたウインドウのフォルダをそのページにドラッグするか、「パッケージ化されていない拡張機能を読み込む」をクリックして {dir} を選びます。",
"Drag onto chrome://extensions": "chrome://extensions にドラッグ",
@@ -2532,6 +2544,10 @@ magpie.strings({
"Not set up: set up the extension in Chrome, Edge, Arc, Brave or another Chromium browser": "Nicht eingerichtet: Richte die Erweiterung in Chrome, Edge, Arc, Brave oder einem anderen Chromium-Browser ein",
"Open chrome://extensions (edge://extensions in Edge) in the browser you use every day.": "Öffne chrome://extensions (in Edge edge://extensions) in dem Browser, den du täglich nutzt.",
"Turn on Developer mode.": "Schalte den Entwicklermodus ein.",
"Not connected: download the extension and load it in your browser": "Nicht verbunden: Lade die Erweiterung herunter und lade sie in deinem Browser",
"Download the extension": "Erweiterung herunterladen",
"Unzip the download.": "Entpacke den Download.",
"Click Load unpacked and choose the unzipped Magpie Browser Extension folder.": "Klicke auf „Entpackte Erweiterung laden“ und wähle den entpackten Ordner Magpie Browser Extension.",
"Drag the folder below onto that page.": "Ziehe den Ordner unten auf diese Seite.",
"Drag the folder from the window that opened onto that page, or click Load unpacked and choose {dir}.": "Ziehe den Ordner aus dem geöffneten Fenster auf diese Seite, oder klicke auf „Entpackte Erweiterung laden“ und wähle {dir}.",
"Drag onto chrome://extensions": "Auf chrome://extensions ziehen",
+94 -1
View File
@@ -3,11 +3,14 @@ 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"
)
@@ -31,6 +34,64 @@ type browserJSON struct {
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 {
@@ -67,7 +128,39 @@ func browserState(ctx context.Context) browserJSON {
func browserRoutes(mux *http.ServeMux, w Windows) {
mux.HandleFunc("GET /api/library/browser", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, browserState(r.Context()))
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
+116
View File
@@ -0,0 +1,116 @@
package gui
import (
"archive/zip"
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/gateway"
)
// A browser magpie's folders are out of reach of downloads the extension,
// pointed at the page's own address and given a gateway key of its own,
// the same key each time while it is on.
func TestBrowserExtensionDownload(t *testing.T) {
sandboxHome(t)
mux := http.NewServeMux()
browserRoutes(mux, folderOnly{})
download := func(body string) (int, string) {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/library/browser/extension", strings.NewReader(body)))
if w.Code != 200 {
return w.Code, ""
}
if got := w.Header().Get("Content-Disposition"); got != `attachment; filename="Magpie Browser Extension.zip"` {
t.Errorf("Content-Disposition %q", got)
}
zr, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len()))
if err != nil {
t.Fatal(err)
}
for _, f := range zr.File {
if f.Name == "Magpie Browser Extension/config.js" {
rc, _ := f.Open()
b, _ := io.ReadAll(rc)
rc.Close()
return 200, string(b)
}
}
t.Fatal("no config.js in the zip")
return 0, ""
}
keyOf := func(config string) string {
m := regexp.MustCompile(`KEY = "([^"]*)"`).FindStringSubmatch(config)
if m == nil {
t.Fatalf("no KEY in %q", config)
}
return m[1]
}
_, config := download(`{"at":"http://localhost:3430"}`)
if !strings.Contains(config, `GATEWAY = "ws://localhost:3430"`) {
t.Fatalf("config %q isn't pointed at the page's address", config)
}
first := keyOf(config)
who, ok := access.Authenticate(first)
if !ok {
t.Fatalf("the zip's key %q isn't a gateway key", first)
}
if got := gateway.OwnBrowserKey(); got != who.KeyID {
t.Fatalf("the own browser key recorded is %q, want %q", got, who.KeyID)
}
_, config = download(`{"at":"https://magpie.example.com/"}`)
if !strings.Contains(config, `GATEWAY = "wss://magpie.example.com"`) || keyOf(config) != first {
t.Fatalf("a second download got %q, want the same key at wss", config)
}
if keys, _ := access.List(); len(keys) != 1 || keys[0].Name != browserKeyName {
t.Fatalf("keys after two downloads: %+v", keys)
}
// a key turned off isn't handed out again
if _, err := access.Update("off-key", access.Change{Key: who.KeyID}); err != nil {
t.Fatal(err)
}
_, config = download(`{"at":"http://localhost:3430"}`)
if again := keyOf(config); again == first {
t.Fatal("a key turned off was put in the extension again")
} else if w, ok := access.Authenticate(again); !ok {
t.Fatal("the new key isn't on")
} else if gateway.OwnBrowserKey() != w.KeyID {
t.Fatal("the new key isn't recorded as the own browser's")
}
for _, at := range []string{"ftp://x", "http://u:p@x:1", "http://x/path", "http://x?k=1", "javascript:alert(1)"} {
b, _ := json.Marshal(map[string]string{"at": at})
if code, _ := download(string(b)); code != http.StatusBadRequest {
t.Errorf("at %q: %d, want 400", at, code)
}
}
}
// Away: a page looked at from another computer downloads the extension.
func TestBrowserAwayFromAnotherComputer(t *testing.T) {
sandboxHome(t)
mux := http.NewServeMux()
browserRoutes(mux, folderOnly{})
for addr, want := range map[string]bool{"127.0.0.1:5000": false, "[::1]:5000": false, "192.168.1.20:5000": true} {
r := httptest.NewRequest("GET", "/api/library/browser", nil)
r.RemoteAddr = addr
w := httptest.NewRecorder()
mux.ServeHTTP(w, r)
var b browserJSON
if err := json.Unmarshal(w.Body.Bytes(), &b); err != nil {
t.Fatal(err)
}
// a test run inside a container is away from every page
if b.Away != want && !(b.Away && !want && gateway.InContainer()) {
t.Errorf("%s: away %v, want %v", addr, b.Away, want)
}
}
}
@@ -0,0 +1,138 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Magpie Browser's sheet looked at from a browser magpie's folders are out
// of reach of: magpie in a container (Docker) or on another computer. The
// folder it writes can't be loaded there, so the sheet offers Download the
// extension, which posts the page's own address and gets the extension as
// a zip pointed at it with a gateway key of its own, and the steps to load
// the unzipped folder. No folder is shown, and nothing is written here.
// Once the browser connects the sheet says so. Every language, Chromium
// and WebKit, at 1100 and 420 wide, nothing running off to the side; no
// backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { strings } = require("./strings.cjs");
const assets = path.resolve(__dirname, "../assets");
const { I18N } = strings();
const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
const tr = (lang, s, vars = {}) => Object.entries(vars).reduce((o, [k, v]) => o.replace(`{${k}}`, v), lang === "en" ? s : I18N[lang]?.[s] ?? s);
const HOME = "/Users/tester";
const DIR = `${HOME}/Magpie Browser Extension`;
const ABOUT = "Use your own browser: your tabs, signed in to the sites you use. Open pages, click, type, upload, read and take screenshots, through the Magpie Browser extension.";
function fixture(lang) {
const st = { connected: false, setups: 0, downloads: [] };
const browser = () => ({ dir: DIR, written: false, version: "0.1.7", connected: st.connected, away: true, ...(st.connected ? { extension: "0.1.7", browser: "Chrome/141" } : {}) });
const route = async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/library") {
return json({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color", mcp: `${HOME}/.claude.json`, skills: `${HOME}/.claude/skills` }],
instructions: { agents: [], sets: [] }, servers: [], foundServers: [], projects: [], foundSkills: [], skills: [], problems: [],
});
}
if (url.pathname === "/api/library/market/servers") {
return json({ items: [
{ id: "magpie-browser", name: "magpie-browser", title: "Magpie Browser", publisher: "Magpie", description: ABOUT, transport: "stdio", runs: "magpie", featured: true, optIn: true, have: "" },
{ id: "fetch", name: "fetch", title: "Fetch", description: "Read the web.", transport: "stdio", runs: "uvx", featured: true, have: "" },
] });
}
if (url.pathname === "/api/library/market/skills") return json({ items: [] });
if (url.pathname === "/api/library/browser") return json(browser());
if (url.pathname === "/api/library/browser/setup") { st.setups++; return json(browser()); }
if (url.pathname === "/api/library/browser/extension" && req.method() === "POST") {
st.downloads.push(JSON.parse(req.postData() || "{}"));
return route.fulfill({ contentType: "application/zip", headers: { "Content-Disposition": 'attachment; filename="Magpie Browser Extension.zip"' }, body: Buffer.from("PK\x05\x06" + "\0".repeat(18), "binary") });
}
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
const body = await fs.readFile(file).catch(() => null);
await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" }));
};
return { route, st };
}
const wide = (page) => page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": away from magpie, Magpie Browser's sheet downloads the extension", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const shots = [];
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
for (const [name, buf] of shots) await fs.writeFile(path.join(process.env.ARTIFACT_DIR, `${engine}-library-browser-away-${name}.png`), buf);
}
await browser.close();
});
for (const lang of LANGS) {
const w = (s, vars) => tr(lang, s, vars);
for (const width of [1100, 420]) {
await t.test(`${lang} at ${width}px: download, then connected`, async () => {
const f = fixture(lang);
const context = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce", acceptDownloads: true });
const page = await context.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", f.route);
await page.addInitScript(() => { localStorage.setItem("magpie.libTab", "mcp"); });
await page.goto("http://magpie.test:3430/?view=library");
await page.locator('#view-library .mk[data-market="mcp"] .mk-card[data-id="magpie-browser"]').click();
const sheet = page.locator("#modal .mk-sheet");
await sheet.waitFor();
const box = sheet.locator(".mk-browser");
const state = box.locator(".mk-browser-state");
const go = box.locator("button");
await page.waitForFunction((s) => document.querySelector("#modal .mk-browser-state")?.textContent === s,
w("Not connected: download the extension and load it in your browser"));
assert.equal((await go.textContent()).trim(), w("Download the extension"));
assert.equal(await box.locator(".mk-browser-steps").isVisible(), false);
assert.equal(await box.locator(".mk-browser-folder").isVisible(), false);
assert.equal(await wide(page), 0);
shots.push([`${lang}-${width}-new`, await sheet.screenshot()]);
const [download] = await Promise.all([page.waitForEvent("download"), go.click()]);
assert.equal(download.suggestedFilename(), "Magpie Browser Extension.zip");
// the page's own address, whose port hands the gateway's routes on
assert.deepEqual(f.st.downloads, [{ at: "http://magpie.test:3430" }]);
assert.equal(f.st.setups, 0, "nothing is written on magpie's side");
assert.deepEqual(await box.locator(".mk-browser-steps li").allTextContents(), [
w("Unzip the download."),
w("Open chrome://extensions (edge://extensions in Edge) in the browser you use every day."),
w("Turn on Developer mode."),
w("Click Load unpacked and choose the unzipped Magpie Browser Extension folder."),
]);
assert.equal(await box.locator(".mk-browser-steps").isVisible(), true);
assert.equal(await box.locator(".mk-browser-folder").isVisible(), false);
assert.equal(await wide(page), 0);
assert.equal(await sheet.evaluate((e) => e.scrollWidth - e.clientWidth), 0);
shots.push([`${lang}-${width}-downloaded`, await sheet.screenshot()]);
f.st.connected = true;
await page.waitForFunction((s) => document.querySelector("#modal .mk-browser-state")?.textContent === s,
w("Connected to your browser") + " · 0.1.7", { timeout: 10000 });
assert.equal(await state.locator(".mk-browser-dot.on").count(), 1);
assert.equal(await box.locator(".mk-browser-steps").isVisible(), false);
assert.equal(await wide(page), 0);
assert.deepEqual(errors, []);
await context.close();
});
}
}
});
}
+1 -1
View File
@@ -176,7 +176,7 @@ func writeCards(m map[string]hubCard) {
// for, else what it says of itself; its title; and its tools but those
// turned off, as it last listed them.
func hubServerOf(s *Server) gateway.HubServer {
out := gateway.HubServer{Name: s.Name, About: serverAbout(s), Bridge: s.Bridge != "", HereOnly: hereOnly(s), Program: s.Plugin != "" || !s.Remote()}
out := gateway.HubServer{Name: s.Name, About: serverAbout(s), Bridge: s.Bridge != "", HereOnly: hereOnly(s), Program: s.Plugin != "" || !s.Remote(), Keyed: keepsSession(s) && !s.Remote()}
c := cardOf(s)
if c == nil {
return out
+8
View File
@@ -844,5 +844,13 @@ func TestHubKeepsThisComputersOwnServersHere(t *testing.T) {
if got := hubServerOf(&c.s); got.HereOnly != c.here || got.Program != c.program {
t.Errorf("%+v: here-only %v program %v, want %v %v", c.s, got.HereOnly, got.Program, c.here, c.program)
}
// only Magpie Browser's browsers are a gateway key's (gateway.HubServer's Keyed)
if got, want := hubServerOf(&c.s).Keyed, len(c.s.Args) > 1 && c.s.Args[1] == "browser"; got != want {
t.Errorf("%+v: keyed %v, want %v", c.s, got, want)
}
}
keyed := gateway.WithHubVisitor(here, gateway.HubVisitor{Away: true, Key: "k1"})
if got := servers(keyed); !slices.Equal(got, []string{"fake", browserServerName}) && !slices.Equal(got, []string{browserServerName, "fake"}) {
t.Errorf("listed for a key from elsewhere: %v", got)
}
}
+5
View File
@@ -80,6 +80,7 @@
<a href="#run">Run it</a>
<a href="#web">The browser UI</a>
<a href="#signin">Sign in to subscriptions</a>
<a href="#browser">Your own browser</a>
<a href="#volume">What is kept</a>
<a href="#env">Environment</a>
<a href="#share">Gateway keys and other machines</a>
@@ -150,6 +151,10 @@ docker logs magpie</pre>
</div>
<p>A Grok (SuperGrok) subscription signs in through xAI’s Grok Build CLI, which the image doesn’t have either. Its sign-in, in the browser UI or with <code>magpie plugin login grok</code>, installs it first, as xAI’s installer does: the stable version from <code>x.ai/cli</code>, kept in <code>/config/home/.grok</code>. To use a Grok Build binary you put on the volume yourself, set <code>GROK_BIN_DIR</code> to the folder holding it.</p>
<h2 id="browser"><a class="anchor" href="#browser">Your own browser</a></h2>
<p>Magpie Browser lets agents act in your own browser, through its extension. The extension can’t be loaded from the container’s folders, so in the browser UI open <span class="ui">Library</span> → <span class="ui">Magpie Browser</span> and click <span class="ui">Download the extension</span>. The zip is pointed at the page’s own address, with a gateway key named <b>Magpie Browser</b> of its own. Unzip it, open <code>chrome://extensions</code>, turn on Developer mode and click <span class="ui">Load unpacked</span> on the unzipped folder. An extension already loaded takes the address (<code>http://localhost:3430</code>, or the gateway’s published port) and a gateway key in its popup.</p>
<p>The browser connected with the downloaded extension is the container’s own: agents in the container use it, and so does an agent on the host that calls <code>/mcp/magpie/browser</code> with the same Magpie Browser key. A browser given another key is that key’s alone.</p>
<h2 id="volume"><a class="anchor" href="#volume">What is kept</a></h2>
<p>Everything magpie writes is under <code>/config</code>, so a restart, or a new container on the same volume, keeps your providers, keys, sign-ins and plugins.</p>
<div class="table-wrap"><table>
+5
View File
@@ -80,6 +80,7 @@
<a href="#run">起動する</a>
<a href="#web">ブラウザ UI</a>
<a href="#signin">サブスクリプションにサインイン</a>
<a href="#browser">自分のブラウザ</a>
<a href="#volume">保存されるもの</a>
<a href="#env">環境変数</a>
<a href="#share">ゲートウェイキーとほかのマシン</a>
@@ -150,6 +151,10 @@ docker logs magpie</pre>
</div>
<p>Grok(SuperGrok)サブスクリプションは xAI の Grok Build CLI でサインインしますが、これもイメージにはありません。ブラウザ UI や <code>magpie plugin login grok</code> でサインインすると、magpie が xAI のインストーラーと同じ方法で先にインストールします。<code>x.ai/cli</code> の stable 版を <code>/config/home/.grok</code> に置きます。自分でボリュームに置いた Grok Build を使うときは、<code>GROK_BIN_DIR</code> にそのフォルダを指定します。</p>
<h2 id="browser"><a class="anchor" href="#browser">自分のブラウザ</a></h2>
<p>Magpie Browser は拡張機能を通して、エージェントにあなた自身のブラウザを操作させます。コンテナ内のフォルダは拡張機能として読み込めないので、ブラウザ UI で <span class="ui">ライブラリ</span> → <span class="ui">Magpie Browser</span> を開き、<span class="ui">拡張機能をダウンロード</span> をクリックします。zip はこのページ自身のアドレスを指し、<b>Magpie Browser</b> という名前の専用ゲートウェイキーが入っています。展開して <code>chrome://extensions</code> を開き、デベロッパー モードをオンにして、展開したフォルダを <span class="ui">パッケージ化されていない拡張機能を読み込む</span> で選びます。読み込み済みの拡張機能は、ポップアップでアドレス(<code>http://localhost:3430</code> か、ゲートウェイを公開したポート)とゲートウェイキーを受け付けます。</p>
<p>ダウンロードした拡張機能で接続したブラウザはコンテナ自身のものです。コンテナ内のエージェントが使い、同じ Magpie Browser キーで <code>/mcp/magpie/browser</code> を呼ぶホストのエージェントも使えます。別のキーで接続したブラウザは、そのキーだけのものです。</p>
<h2 id="volume"><a class="anchor" href="#volume">保存されるもの</a></h2>
<p>magpie が書くものはすべて <code>/config</code> の下にあるので、再起動しても、同じボリュームで新しいコンテナを作っても、プロバイダ、キー、サインイン、プラグインは残ります。</p>
<div class="table-wrap"><table>
+5
View File
@@ -80,6 +80,7 @@
<a href="#run">运行</a>
<a href="#web">Web 界面</a>
<a href="#signin">登录订阅</a>
<a href="#browser">你自己的浏览器</a>
<a href="#volume">保存了什么</a>
<a href="#env">环境变量</a>
<a href="#share">网关密钥与其他机器</a>
@@ -150,6 +151,10 @@ docker logs magpie</pre>
</div>
<p>Grok(SuperGrok)订阅通过 xAI 的 Grok Build CLI 登录,镜像里同样没有它。在浏览器界面里登录,或者用 <code>magpie plugin login grok</code> 登录时,magpie 会先按 xAI 安装脚本的方式安装它:从 <code>x.ai/cli</code> 下载 stable 版本,放在 <code>/config/home/.grok</code>。要用你自己放进数据卷的 Grok Build,把 <code>GROK_BIN_DIR</code> 设为它所在的文件夹。</p>
<h2 id="browser"><a class="anchor" href="#browser">你自己的浏览器</a></h2>
<p>Magpie Browser 通过它的扩展,让 Agent 在你自己的浏览器里操作。容器里的文件夹没法直接加载成扩展,所以在浏览器界面打开 <span class="ui">资源库</span> → <span class="ui">Magpie Browser</span>,点 <span class="ui">下载扩展</span>。下载的 zip 指向这个页面自己的地址,并带一个名为 <b>Magpie Browser</b> 的专用网关密钥。解压后打开 <code>chrome://extensions</code>,打开开发者模式,点 <span class="ui">加载已解压的扩展程序</span>,选择解压出的文件夹。已经加载过的扩展,也可以在它的弹窗里填地址(<code>http://localhost:3430</code>,或网关发布到主机的端口)和网关密钥。</p>
<p>用下载的扩展连上的浏览器就是这个容器自己的:容器里的 Agent 直接用它,主机上用同一个 Magpie Browser 密钥调用 <code>/mcp/magpie/browser</code> 的 Agent 也能用。填了别的密钥连上的浏览器只属于那个密钥。</p>
<h2 id="volume"><a class="anchor" href="#volume">保存了什么</a></h2>
<p>magpie 写的所有东西都在 <code>/config</code> 下,所以重启、或者在同一个数据卷上新建容器,供应商、密钥、登录和插件都还在。</p>
<div class="table-wrap"><table>