From 6c201095d85b3a6f956b4e32da5cc80abe64b642 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 3 Nov 2026 18:50:06 +0800 Subject: [PATCH] gateway: in Docker, other containers on the host are shown the host's Docker bridge address jiezhengj (Discord #feedback) runs magpie in Docker on a NAS at 192.168.31.218. The web UI's host address, http://192.168.31.218:3425, works for other devices. Other containers on the NAS couldn't use it, and not the container's own 172.17.0.x either. What works for them is the host's Docker bridge address, http://172.17.0.1:3425. On Linux, host.docker.internal is there only in a container given extra_hosts. magpie showed no such address. - gateway.ContainerHostURL: in a container on a bridge network, the gateway of /proc/net/route's default route (172.17.0.1 on the default bridge, a compose network's own otherwise), on the gateway's port. It is "" outside a container and on the host's network (`network_mode: host`, told by the host's docker0/br-*/veth*/podman* interfaces). In that case ContainerAddrs is false too, since the addresses are the host's own. - The GUI gets it as /api/providers' gateway.containerHost, /api/settings' lanContainerHost and boot's sideGateway.containerHost. - settings.js lanShown is fed by the new gwLAN(g) for Gateway, Connect, the sidebar and the key page. Each case lists: - Opened at the host: the host's address first, then the bridge address, labelled "Other containers on this host". - At localhost: the bridge address alone, with that label, and a line that the host's own is MAGPIE_PUBLIC_URL's. - No default route: as before. The container's own 172.17.0.x is no longer offered beside them. The sidebar line and the key page prefer an address other machines reach. The scheme comes from the URL, not a hard-coded http. Three new strings are in zh, zh-TW, ja and de. - CLI: `magpie web` and the share banner print "other containers on this host ". - docs/reference.md and site docs/docker (en, zh, ja): the log example and a new "Other containers on the same host" paragraph. Run on mote, at this change on d8501848a: - gofmt -l: clean. node --check: passes. - Vet: darwin go vet, GOOS=linux go vet -tags nogui and GOOS=windows go vet of internal/gateway, internal/gui and internal/cli: ok. - go test -timeout 45m: internal/gateway ok. internal/gui is red only on TestMainWindowCorners/macOS_26_SDK, which is red on macOS 27 at main (#3949). internal/cli is red only on TestEveryRouteHasACommandOrIsNamed for GET /api/context/reply, red at main (#5026). - GUI, chromium and webkit: lan-docker (en, zh, zh-TW, ja, de) and the 40 files on the caller-keys fixture or the LAN paths. 586 tests, 580 pass. Each red is also red alone at the base d8501848a or af9ac3d25: - phone-connect-menu 420, 4 reds (#4706, #4707). - gateway-key-models webkit en (#4616, #4081; 4 of 4 at the base). - gateway-caller-keys chromium en (#3797; 2 of 3 at the base, 1 of 3 here). After the rebase onto 3f1f1882a (187f3e272, the usage page alone, came after): the commits between touch none of these files. Linux and Windows vet ok. go test -run 'Container|HostNetwork|DefaultGateway|PublicURL|LAN|Boot|Provider' ok in gateway, gui and cli. GUI lan-docker, i18n-keys, side-gateway-lan and key-page: 56 of 56, in both engines. Broken by hand, in a copy: - defaultGateway reading big-endian: TestDefaultGateway goes red ("1.0.17.172"). - The old settings.js, client.js and keys.js: every lan-docker test goes red, in both engines and every language. TestDefaultGateway stubs the in-container check, so it tests the container path on mote and CI too. Not tried: - a real Docker container, on a NAS or anywhere; - reaching 172.17.0.1 from a container on another compose network on the reporter's NAS; - a published port that differs from the gateway's (MAGPIE_PUBLIC_URL sets the host's; the bridge address uses the gateway's own port); - Podman's rootless networking (slirp4netns, pasta), where the default route may not be the host. --- docs/reference.md | 6 + internal/cli/providers_cli.go | 16 ++- internal/cli/web_cli.go | 3 + internal/gateway/lan.go | 91 ++++++++++++- internal/gateway/lan_test.go | 70 ++++++++++ internal/gateway/url_test.go | 2 +- internal/gui/api.go | 11 ++ internal/gui/assets/i18n.js | 12 ++ internal/gui/assets/plugins/gateway/client.js | 13 +- internal/gui/assets/plugins/gateway/keys.js | 2 +- .../gui/assets/plugins/gateway/settings.js | 50 ++++--- internal/gui/providers.go | 8 ++ internal/gui/tests/fixtures/caller-keys.cjs | 12 +- internal/gui/tests/lan-docker.test.cjs | 125 +++++++++++++++--- site/public/docs/docker.html | 2 + site/public/docs/ja/docker.html | 2 + site/public/docs/zh/docker.html | 2 + 17 files changed, 384 insertions(+), 43 deletions(-) diff --git a/docs/reference.md b/docs/reference.md index 419420222..df703b00a 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -2926,6 +2926,12 @@ published on the host) for the address it shows and prints to be the one other machines use; behind a reverse proxy, set it to that external base URL and follow the [authentication requirements above](#connecting-anything-else), especially when the proxy reaches magpie over loopback. +Other containers on the same host reach the gateway at the host's Docker +bridge address on the published port, `http://172.17.0.1:3425` on the default +bridge; magpie reads it from the container's default route and lists it as +"Other containers on this host" (in the browser UI and in `magpie web`'s log). +On Linux `host.docker.internal` is there only for a container given +`extra_hosts: ["host.docker.internal:host-gateway"]`. For the browser UI run the image with `magpie web --addr 0.0.0.0:3430 --no-open` in place of the default `serve`, and open diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index 22a6fb056..0940ecbd0 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -1372,9 +1372,20 @@ func keyNote() string { } // containerNote follows the addresses magpie finds for itself in a -// container, which are the container's own. +// container, which are the container's own: other machines reach it at +// the host's, and other containers on the host at the bridge's gateway +// (jiezhengj on Discord: 172.17.0.1 on a NAS), containerLine's. const containerNote = "these are the container's own addresses: other machines use the host's, and MAGPIE_PUBLIC_URL=http://: puts it here" +// containerLine is where other containers on this host reach the gateway +// while magpie runs in one, "" when that isn't known. +func containerLine() string { + if u := gateway.ContainerHostURL(); u != "" { + return muted.Render(" other containers on this host ") + u + } + return "" +} + // shareLines are where other machines reach the gateway while it is shared // from Settings, for the banner. func shareLines() []string { @@ -1388,6 +1399,9 @@ func shareLines() []string { if gateway.ContainerAddrs() { out = append(out, muted.Render(" "+containerNote)) } + if l := containerLine(); l != "" { + out = append(out, l) + } return out } diff --git a/internal/cli/web_cli.go b/internal/cli/web_cli.go index fc7ea89df..3bfe3566c 100644 --- a/internal/cli/web_cli.go +++ b/internal/cli/web_cli.go @@ -138,6 +138,9 @@ func printWeb(w *gui.Web) { if gateway.ContainerAddrs() { fmt.Println(muted.Render(" " + containerNote)) } + if l := containerLine(); l != "" { + fmt.Println(l) + } fmt.Println(amber.Render("!"), lanWarning()) } else if l := proxyLink(key); l != "" { fmt.Println(muted.Render(" through your proxy"), l) diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index 2bb473923..6af6e719c 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -131,8 +131,95 @@ func PublicHost() string { // ContainerAddrs: the addresses magpie finds for itself are a container's, // which other machines can't reach, and MAGPIE_PUBLIC_URL doesn't say the -// host's. -func ContainerAddrs() bool { return publicURL() == "" && inContainer("/") } +// host's. A container on the host's network (network_mode: host, which +// NAS panels offer) has the host's own addresses, and they are said as +// they are. +func ContainerAddrs() bool { + return publicURL() == "" && inContainer("/") && !hostNetwork(ifaceNames()) +} + +// hostNetwork: the interfaces names are the host's, not a container's own: +// a host running containers has their bridges and veth pairs (docker0, +// br-…, veth…, Podman's cni-podman0 or podman0), which a container on a +// bridge network never sees; it has its eth0 alone. +func hostNetwork(names []string) bool { + for _, n := range names { + for _, p := range []string{"docker0", "br-", "veth", "cni-podman", "podman"} { + if strings.HasPrefix(n, p) { + return true + } + } + } + return false +} + +// ifaceNames are this system's network interfaces' names; a variable for +// the tests. +var ifaceNames = func() []string { + ifs, _ := net.Interfaces() + out := make([]string, 0, len(ifs)) + for _, i := range ifs { + out = append(out, i.Name) + } + return out +} + +// ContainerHostURL is where other containers on this host reach the +// gateway while magpie runs in a container on a bridge network: the host +// at the container's default route, the bridge's gateway (Docker's +// 172.17.0.1), on the gateway's port as published. The container's own +// address is reached only from its own Docker network, and the host's LAN +// address may not be reached from a container through the NAS's firewall +// (jiezhengj on Discord: 192.168.31.218 worked from other devices, and +// other containers on the NAS needed 172.17.0.1); host.docker.internal is +// not there on Linux unless a container is given it. "" when magpie is +// not in a container, is on the host's network, or has no default route. +func ContainerHostURL() string { + if !inThisContainer() || hostNetwork(ifaceNames()) { + return "" + } + gw := defaultGateway(routeTable()) + if gw == "" { + return "" + } + return Scheme() + "://" + net.JoinHostPort(gw, Port()) +} + +// inThisContainer is inContainer("/"); a variable for the tests. +var inThisContainer = func() bool { return inContainer("/") } + +// routeTable is Linux's IPv4 routing table; a variable for the tests. +var routeTable = func() string { + b, _ := os.ReadFile("/proc/net/route") + return string(b) +} + +// defaultGateway is the gateway of /proc/net/route's default route: its +// Destination 00000000 with RTF_GATEWAY (0x2) set, the address in the +// kernel's byte order, little-endian on every machine Docker images are +// built for here (amd64, arm64). "" when there is none. +func defaultGateway(table string) string { + for _, line := range strings.Split(table, "\n") { + f := strings.Fields(line) + if len(f) < 4 || f[1] != "00000000" { + continue + } + flags, err := strconv.ParseUint(f[3], 16, 16) + if err != nil || flags&0x2 == 0 { + continue + } + v, err := strconv.ParseUint(f[2], 16, 32) + if err != nil || v == 0 { + continue + } + ip := netip.AddrFrom4([4]byte{byte(v), byte(v >> 8), byte(v >> 16), byte(v >> 24)}) + if ip.IsLoopback() || ip.IsUnspecified() { + continue + } + return ip.String() + } + return "" +} // InContainer: this magpie runs in a container (Docker, Podman, a // Kubernetes pod), whose image is what gets updated, not its binary. diff --git a/internal/gateway/lan_test.go b/internal/gateway/lan_test.go index bacc654da..b3d14cad7 100644 --- a/internal/gateway/lan_test.go +++ b/internal/gateway/lan_test.go @@ -201,6 +201,36 @@ func TestInContainer(t *testing.T) { } } +// A container on the host's network (network_mode: host, as NAS panels +// offer) sees the host's interfaces, Docker's bridges among them, and its +// addresses are the host's: they aren't said to be a container's own. A +// container on a bridge network has its eth0 alone (jiezhengj on Discord: +// magpie in Docker on a NAS). +func TestHostNetwork(t *testing.T) { + for _, c := range []struct { + names []string + want bool + }{ + {[]string{"lo", "eth0"}, false}, + {[]string{"lo", "eth0", "eth1"}, false}, + {[]string{"lo", "eth0", "docker0", "br-3f1c2a9b0d4e", "veth1a2b3c4"}, true}, + {[]string{"lo", "ovs_eth0", "docker0"}, true}, + {[]string{"lo", "enp3s0", "cni-podman0"}, true}, + {[]string{"lo", "eth0", "podman0"}, true}, + } { + if got := hostNetwork(c.names); got != c.want { + t.Errorf("%v: %v, want %v", c.names, got, c.want) + } + } + was := ifaceNames + t.Cleanup(func() { ifaceNames = was }) + t.Setenv("MAGPIE_PUBLIC_URL", "") + ifaceNames = func() []string { return []string{"lo", "eth0", "docker0"} } + if ContainerAddrs() { + t.Error("on the host's network, the addresses are said to be a container's") + } +} + // Another computer lists the models with the key it was given whatever // else its client sends beside it: an empty or placeholder Authorization // with the key in x-api-key, a stale token there, "bearer" in lower case @@ -389,3 +419,43 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) { t.Fatal("loopback:", c, b) } } + +// TestDefaultGateway reads the bridge's gateway from a container's +// /proc/net/route, as Docker's default bridge writes it (jiezhengj's NAS: +// other containers reach the host at 172.17.0.1). +func TestDefaultGateway(t *testing.T) { + const docker = "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n" + + "eth0\t00000000\t010011AC\t0003\t0\t0\t0\t00000000\t0\t0\t0\n" + + "eth0\t000011AC\t00000000\t0001\t0\t0\t0\t0000FFFF\t0\t0\t0\n" + for _, c := range []struct{ name, table, want string }{ + {"docker's default bridge", docker, "172.17.0.1"}, + {"a compose network", "Iface\tDestination\tGateway\tFlags\neth0\t000013AC\t00000000\t0001\neth0\t00000000\t010013AC\t0003\n", "172.19.0.1"}, + {"no default route", "Iface\tDestination\tGateway\tFlags\neth0\t000011AC\t00000000\t0001\n", ""}, + {"a default route without a gateway", "Iface\tDestination\tGateway\tFlags\neth0\t00000000\t00000000\t0001\n", ""}, + {"no table (not Linux)", "", ""}, + } { + if got := defaultGateway(c.table); got != c.want { + t.Errorf("%s: %q, want %q", c.name, got, c.want) + } + } + // in a container it is offered on the gateway's port; on the host's + // network, where the addresses are the host's own, it is not + t.Cleanup(func(rt func() string, ifn func() []string, in func() bool) func() { + return func() { routeTable, ifaceNames, inThisContainer = rt, ifn, in } + }(routeTable, ifaceNames, inThisContainer)) + routeTable = func() string { return docker } + ifaceNames = func() []string { return []string{"lo", "eth0"} } + inThisContainer = func() bool { return true } + if got, want := ContainerHostURL(), Scheme()+"://172.17.0.1:"+Port(); got != want { + t.Errorf("in a container: %q, want %q", got, want) + } + ifaceNames = func() []string { return []string{"lo", "eth0", "docker0"} } + if got := ContainerHostURL(); got != "" { + t.Errorf("on the host's network: %q, want none", got) + } + ifaceNames = func() []string { return []string{"lo", "eth0"} } + inThisContainer = func() bool { return false } + if got := ContainerHostURL(); got != "" { + t.Errorf("not in a container: %q, want none", got) + } +} diff --git a/internal/gateway/url_test.go b/internal/gateway/url_test.go index b22b5c58f..3fa8eb1ce 100644 --- a/internal/gateway/url_test.go +++ b/internal/gateway/url_test.go @@ -60,7 +60,7 @@ func TestPublicURL(t *testing.T) { if got := PublicHost(); got != "" { t.Errorf("invalid public host: %q", got) } - if got := ContainerAddrs(); got != inContainer("/") { + if got := ContainerAddrs(); got != (inContainer("/") && !hostNetwork(ifaceNames())) { t.Errorf("invalid URL must be treated as unset in a container: %v", got) } for _, got := range LANURLs() { diff --git a/internal/gui/api.go b/internal/gui/api.go index ab6d9eb3a..573ef60e2 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -511,6 +511,9 @@ type settingsJSON struct { // LANURLs are a container's own addresses, not the host's: the page // offers the one it was opened at instead, or says how to set it LANContainer bool `json:"lanContainer,omitempty"` + // where other containers on this host reach the gateway while magpie + // runs in one (gateway.ContainerHostURL) + LANContainerHost string `json:"lanContainerHost,omitempty"` // those of LANURLs at an internet address, which anyone online can // reach, not only this network LANPublic []string `json:"lanPublic,omitempty"` @@ -771,6 +774,7 @@ func settingsState() settingsJSON { s.Login, s.LoginAllow = login != autostart.Off, login == autostart.NeedsAllowing if s.LAN { s.LANURLs, s.LANContainer = gateway.LANURLs(), gateway.ContainerAddrs() + s.LANContainerHost = gateway.ContainerHostURL() s.LANPublic = gateway.PublicURLs(s.LANURLs) } s.CodexWarmed, s.ClaudeWarmed = latest(provider.CodexWarmed()), latest(provider.ClaudeWarmed()) @@ -1031,6 +1035,13 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { // window's line names from the first paint (coeo91 on Discord) if s.LAN || gateway.OnNetwork() { side["lan"], side["lanURLs"] = true, gateway.LANURLs() + // in a container they are its own: the line names the host's + if gateway.ContainerAddrs() { + side["container"] = true + } + if u := gateway.ContainerHostURL(); u != "" { + side["containerHost"] = u + } if u := gateway.PublicURL(); u != "" { side["publicURL"] = u } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 63c589d63..f376b8a14 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1123,6 +1123,9 @@ const I18N = { "In a container": "在容器中运行", "Where this page was opened, on the gateway’s port; MAGPIE_PUBLIC_URL sets another": "打开本页所用的地址,端口为网关端口;可用 MAGPIE_PUBLIC_URL 另设", "The container’s own addresses, which other devices can’t reach: set MAGPIE_PUBLIC_URL to the host’s": "容器自身的地址,其他设备无法访问:请将 MAGPIE_PUBLIC_URL 设为宿主机地址", + "Other devices use the host’s address this page was opened at, and other containers on this host the host’s Docker bridge address, both on the gateway’s port; MAGPIE_PUBLIC_URL sets another": "其他设备用打开这个页面所用的宿主机地址,本机上的其他容器用宿主机的 Docker bridge 地址,端口都是网关的端口;MAGPIE_PUBLIC_URL 可另设", + "Other containers on this host use the host’s Docker bridge address, on the gateway’s port; other devices use the host’s own, which MAGPIE_PUBLIC_URL puts here": "本机上的其他容器用宿主机的 Docker bridge 地址,端口是网关的端口;其他设备用宿主机自己的地址,用 MAGPIE_PUBLIC_URL 把它设在这里", + "Other containers on this host": "同一主机上的其他容器", "New key": "换新 Key", "API keys, private keys, tokens and passwords go to vendors as placeholders, and come back as they were": "API Key、私钥、Token 和密码以占位符发给模型厂商,回复里再还原", "Mask personal data": "脱敏个人信息", @@ -5681,6 +5684,9 @@ const I18N = { "In a container": "在容器中執行", "Where this page was opened, on the gateway’s port; MAGPIE_PUBLIC_URL sets another": "開啟本頁所用的位址,連接埠為閘道連接埠;可用 MAGPIE_PUBLIC_URL 另設", "The container’s own addresses, which other devices can’t reach: set MAGPIE_PUBLIC_URL to the host’s": "容器自身的位址,其他裝置無法存取:請將 MAGPIE_PUBLIC_URL 設為宿主機位址", + "Other devices use the host’s address this page was opened at, and other containers on this host the host’s Docker bridge address, both on the gateway’s port; MAGPIE_PUBLIC_URL sets another": "其他裝置使用開啟此頁面所用的主機位址,本機上的其他容器使用主機的 Docker bridge 位址,連接埠都是閘道的連接埠;MAGPIE_PUBLIC_URL 可另設", + "Other containers on this host use the host’s Docker bridge address, on the gateway’s port; other devices use the host’s own, which MAGPIE_PUBLIC_URL puts here": "本機上的其他容器使用主機的 Docker bridge 位址,連接埠是閘道的連接埠;其他裝置使用主機自己的位址,用 MAGPIE_PUBLIC_URL 把它設在這裡", + "Other containers on this host": "同一主機上的其他容器", "New key": "換新 Key", "API keys, private keys, tokens and passwords go to vendors as placeholders, and come back as they were": "API Key、私鑰、Token 和密碼以佔位符發給模型廠商,回覆裡再還原", "Mask personal data": "脫敏個人資訊", @@ -10210,6 +10216,9 @@ const I18N = { "In a container": "コンテナ内", "Where this page was opened, on the gateway’s port; MAGPIE_PUBLIC_URL sets another": "このページを開いたアドレス(ゲートウェイのポート)。MAGPIE_PUBLIC_URL で別のアドレスを設定できます", "The container’s own addresses, which other devices can’t reach: set MAGPIE_PUBLIC_URL to the host’s": "コンテナ自身のアドレスで、他のデバイスからは到達できません。MAGPIE_PUBLIC_URL にホストのアドレスを設定してください", + "Other devices use the host’s address this page was opened at, and other containers on this host the host’s Docker bridge address, both on the gateway’s port; MAGPIE_PUBLIC_URL sets another": "ほかのデバイスはこのページを開いたホストのアドレスを、このホストのほかのコンテナはホストの Docker bridge アドレスを使います。どちらもゲートウェイのポートです。MAGPIE_PUBLIC_URL で別のものを設定できます", + "Other containers on this host use the host’s Docker bridge address, on the gateway’s port; other devices use the host’s own, which MAGPIE_PUBLIC_URL puts here": "このホストのほかのコンテナはホストの Docker bridge アドレスをゲートウェイのポートで使います。ほかのデバイスはホスト自身のアドレスを使います。MAGPIE_PUBLIC_URL でそれをここに表示できます", + "Other containers on this host": "同じホストのほかのコンテナ", "New key": "新しいキー", "API keys, private keys, tokens and passwords go to vendors as placeholders, and come back as they were": "APIキー、秘密鍵、トークン、パスワードはプレースホルダーとしてベンダーに送られ、元どおりに戻されます", "Mask personal data": "個人情報をマスク", @@ -14754,6 +14763,9 @@ const I18N = { "In a container": "In einem Container", "Where this page was opened, on the gateway’s port; MAGPIE_PUBLIC_URL sets another": "Wo diese Seite geöffnet wurde, auf dem Port des Zugangspunkts; MAGPIE_PUBLIC_URL legt eine andere fest", "The container’s own addresses, which other devices can’t reach: set MAGPIE_PUBLIC_URL to the host’s": "Die eigenen Adressen des Containers, für andere Geräte nicht erreichbar: MAGPIE_PUBLIC_URL auf die des Hosts setzen", + "Other devices use the host’s address this page was opened at, and other containers on this host the host’s Docker bridge address, both on the gateway’s port; MAGPIE_PUBLIC_URL sets another": "Andere Geräte nutzen die Adresse des Hosts, unter der diese Seite geöffnet wurde, andere Container auf diesem Host die Docker-Bridge-Adresse des Hosts, beide auf dem Port des Gateways; MAGPIE_PUBLIC_URL legt eine andere fest", + "Other containers on this host use the host’s Docker bridge address, on the gateway’s port; other devices use the host’s own, which MAGPIE_PUBLIC_URL puts here": "Andere Container auf diesem Host nutzen die Docker-Bridge-Adresse des Hosts auf dem Port des Gateways; andere Geräte nutzen die eigene Adresse des Hosts, die MAGPIE_PUBLIC_URL hier einträgt", + "Other containers on this host": "Andere Container auf diesem Host", "New key": "Neuer Schlüssel", "API keys, private keys, tokens and passwords go to vendors as placeholders, and come back as they were": "API-Schlüssel, private Schlüssel, Token und Passwörter gehen als Platzhalter an Anbieter und kommen unverändert zurück", "Mask personal data": "Personenbezogene Daten maskieren", diff --git a/internal/gui/assets/plugins/gateway/client.js b/internal/gui/assets/plugins/gateway/client.js index 8994e5e3e..669d168eb 100644 --- a/internal/gui/assets/plugins/gateway/client.js +++ b/internal/gui/assets/plugins/gateway/client.js @@ -278,12 +278,15 @@ function renderGatewayLan() { const shown = web && g.publicURL || g.url; line(t(shown === g.url ? "This computer" : "Public address"), shown); if (g.lan) { - const { urls, sub } = lanShown(g.lanURLs || [], prefs?.lanContainer); + const { urls, others, sub } = gwLAN(g); // an internet address on an interface (an ISP's static one) is said - // to be one, not listed as this network's + // to be one, not listed as this network's, and the one other + // containers on this host use (the host's Docker bridge address) is + // said to be theirs const far = new Set(g.lanPublic || []), rest = urls.filter((u) => u !== shown); - rest.filter((u) => !far.has(u)).forEach((u, i) => line(i ? "" : t("Local network"), u)); - rest.filter((u) => far.has(u)).forEach((u, i) => line(i ? "" : t("On the internet"), u)); + rest.filter((u) => !far.has(u) && !others.includes(u)).forEach((u, i) => line(i ? "" : t("Local network"), u)); + rest.filter((u) => others.includes(u)).forEach((u, i) => line(i ? "" : t("Other containers on this host"), u)); + rest.filter((u) => far.has(u) && !others.includes(u)).forEach((u, i) => line(i ? "" : t("On the internet"), u)); if (!urls.length) list.append(el("div", "gw-url-none", t("This computer has no local network address right now"))); if (sub) list.append(el("div", "gw-url-none", sub)); } @@ -504,7 +507,7 @@ function renderConnect() { // no SDK speaks System One, so it has no shell variables to set const langs = f.baseEnv ? langs4() : langs4().filter(([id]) => id !== "shell"); const snipLang = langs.some(([id]) => id === lang) ? lang : "curl"; - const urls = [g.url, ...(g.lanURLs || [])]; + const urls = [g.url, ...gwLAN(g).urls]; // the address picked is kept (coeo91): an address not offered right now // (the network not up yet after a start) shows this computer's, and the // pick comes back with it. With none picked, MAGPIE_PUBLIC_URL is where diff --git a/internal/gui/assets/plugins/gateway/keys.js b/internal/gui/assets/plugins/gateway/keys.js index e58c06ef1..2619199d1 100644 --- a/internal/gui/assets/plugins/gateway/keys.js +++ b/internal/gui/assets/plugins/gateway/keys.js @@ -297,7 +297,7 @@ function gatewayKeysArrange(list, rows) { // (zytszone on X: a department shares one magpie, whose app its people // can't be given). Its address is the one other machines reach. function gatewayKeyPage() { - const g = providers?.gateway, lan = g?.lanURLs || []; + const g = providers?.gateway, lan = gwFar(g); const at = g?.publicURL || (lan.includes(connectURL) ? connectURL : lan[0]); if (!at || !gatewayKeys?.length) return null; const url = at.replace(/\/+$/, "") + "/me"; diff --git a/internal/gui/assets/plugins/gateway/settings.js b/internal/gui/assets/plugins/gateway/settings.js index 5a2da7e0f..d55209d2f 100644 --- a/internal/gui/assets/plugins/gateway/settings.js +++ b/internal/gui/assets/plugins/gateway/settings.js @@ -273,24 +273,44 @@ let lanSelectedURL = "", lanProtocol = "openai"; // the address picked under Share on local network is kept like Connect's let lanWant = ""; try { lanWant = localStorage.getItem("magpie.lanAddress") || ""; } catch {} -// lanShown: the local network addresses the gateway is offered at, and a -// line on them when magpie runs in a container, for Settings and Gateway -// alike. In a container magpie finds only the container's own addresses; -// the page opened over the network was reached at the host's, so the -// gateway is offered there, on its port. -function lanShown(urls, container) { - if (!container) return { urls, sub: "" }; - const host = location.hostname, port = urls.length ? new URL(urls[0]).port : ""; - if (web && host && port && !/^(localhost|127\.|\[::1\]$)/.test(host)) - return { urls: ["http://" + host + ":" + port], // an IPv6 hostname comes bracketed - sub: t("Where this page was opened, on the gateway’s port; MAGPIE_PUBLIC_URL sets another") }; - return { urls, sub: t("The container’s own addresses, which other devices can’t reach: set MAGPIE_PUBLIC_URL to the host’s") }; +// lanShown: the addresses the gateway is offered at beyond this computer, +// those of them for other containers on this host, and a line on them +// when magpie runs in a container, for Settings, Gateway, Connect, the +// sidebar and the key page alike. In a container magpie finds only its +// own addresses; the page opened over the network was reached at the +// host's, so the gateway is offered there, on its port. Other containers +// on the host reach it at the host's Docker bridge address, the +// container's default route (jiezhengj on Discord: other containers on a +// NAS needed http://172.17.0.1:3425), which follows, said to be theirs. +function lanShown(urls, container, bridge) { + const others = bridge ? [bridge] : []; + if (!container) return { urls: [...urls, ...others.filter((u) => !urls.includes(u))], others, sub: "" }; + const host = location.hostname, at = urls[0] || bridge ? new URL(urls[0] || bridge) : null; + if (web && host && at?.port && !/^(localhost|127\.|\[::1\]$)/.test(host)) + return { urls: [at.protocol + "//" + host + ":" + at.port, ...others], others, // an IPv6 hostname comes bracketed + sub: others.length ? t("Other devices use the host’s address this page was opened at, and other containers on this host the host’s Docker bridge address, both on the gateway’s port; MAGPIE_PUBLIC_URL sets another") + : t("Where this page was opened, on the gateway’s port; MAGPIE_PUBLIC_URL sets another") }; + if (others.length) return { urls: others, others, + sub: t("Other containers on this host use the host’s Docker bridge address, on the gateway’s port; other devices use the host’s own, which MAGPIE_PUBLIC_URL puts here") }; + return { urls, others, sub: t("The container’s own addresses, which other devices can’t reach: set MAGPIE_PUBLIC_URL to the host’s") }; +} +// gwLAN: lanShown for the gateway's read (providers', or boot.js's line), +// which says whether its addresses are a container's and where other +// containers reach it +function gwLAN(g) { + return lanShown(g?.lan && g.lanURLs || [], !!g?.container, g?.lan && g.containerHost || ""); +} +// gwFar: where other machines reach the gateway, for the sidebar and the +// key page: other containers' address only when there is no other +function gwFar(g) { + const { urls, others } = gwLAN(g), far = urls.filter((u) => !others.includes(u)); + return far.length ? far : urls; } // sideLAN: where other machines reach the gateway while it is shared, for // the sidebar's line (coeo91 on Discord): MAGPIE_PUBLIC_URL, else the // address picked here, else the first function sideLAN(g) { - const u = g.lan && g.lanURLs || []; + const u = gwFar(g); return u[0] && (g.publicURL || (u.includes(lanWant) ? lanWant : u[0])); } // the line was drawn from boot.js before this script came @@ -320,7 +340,7 @@ function renderLAN(s) { row(t("Share on local network"), t("Agents on other computers on this network, or through a tunnel to this one such as Cloudflare Tunnel, can use magpie’s models with a gateway key from Gateway"), "", segs([["off", t("Off")], ["on", t("On")]], s.lan ? "on" : "off", (v) => set({ on: v === "on" }))); if (!s.lan) return; - const { urls, sub } = lanShown(s.lanURLs || [], s.lanContainer); + const { urls, others, sub } = lanShown(s.lanURLs || [], s.lanContainer, s.lanContainerHost); if (!urls.length) row(t("Address"), t("This computer has no local network address right now"), ""); else { lanSelectedURL = urls.includes(lanWant) ? lanWant : urls[0]; @@ -337,7 +357,7 @@ function renderLAN(s) { e.stopPropagation(); if (address.classList.contains("open")) return closeProtoMenu(); const suffix = lanProtocol === "openai" ? "/v1" : ""; - openProtoMenu(address, urls.map((u) => ({ v: u, name: u + suffix, note: far.has(u) ? t("On the internet") : "" })), lanSelectedURL, + openProtoMenu(address, urls.map((u) => ({ v: u, name: u + suffix, note: far.has(u) ? t("On the internet") : others.includes(u) ? t("Other containers on this host") : "" })), lanSelectedURL, (v) => { lanSelectedURL = lanWant = v; keepPick("magpie.lanAddress", v); update(); renderSideGw(); }, "Address", "lan-address-menu"); }; } diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 91c2b2540..cdc45a3c2 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -512,6 +512,13 @@ type gatewayJSON struct { // LANPublic are those of LANURLs at an internet address, which anyone // online reaches, not only this network LANPublic []string `json:"lanPublic,omitempty"` + // Container: LANURLs are a container's own addresses, which other + // devices, and containers on other Docker networks, can't reach: the + // page offers the host's it was opened at first (lanShown) + Container bool `json:"container,omitempty"` + // ContainerHost: where other containers on this host reach the + // gateway while magpie runs in one (gateway.ContainerHostURL) + ContainerHost string `json:"containerHost,omitempty"` // OnNetwork: MAGPIE_ADDR puts it beyond loopback (a server, a Docker // image), so every caller is shown a gateway key, and LAN is true too: // callers from elsewhere, a container's host among them, need one @@ -1135,6 +1142,7 @@ func providersState() providersJSON { if s.Gateway.LAN { s.Gateway.LANURLs = gateway.LANURLs() s.Gateway.LANPublic = gateway.PublicURLs(s.Gateway.LANURLs) + s.Gateway.Container, s.Gateway.ContainerHost = gateway.ContainerAddrs(), gateway.ContainerHostURL() if u := gateway.PublicURL(); slices.Contains(s.Gateway.LANURLs, u) { s.Gateway.PublicURL = u } diff --git a/internal/gui/tests/fixtures/caller-keys.cjs b/internal/gui/tests/fixtures/caller-keys.cjs index 6a156b163..f9a8c31b6 100644 --- a/internal/gui/tests/fixtures/caller-keys.cjs +++ b/internal/gui/tests/fixtures/caller-keys.cjs @@ -30,8 +30,14 @@ function fixture(lang, theme, events, options = {}) { const lanPublic = () => lan && options.lanPublic ? { lanPublic: options.lanPublic } : {}; // options.publicURL is MAGPIE_PUBLIC_URL's, offered while shared (#1551) const publicURL = () => lan && options.publicURL ? { publicURL: options.publicURL } : {}; + // options.container: magpie runs in a container, and lanURLs are its + // own; options.containerHost is where other containers on the host + // reach the gateway (the host's Docker bridge address) + const container = () => ({ ...(lan && options.container ? { container: true } : {}), + ...(lan && options.containerHost ? { containerHost: options.containerHost } : {}) }); const lanState = () => ({ lang, theme, lan, - lanURLs: lan ? lanURLs : [], ...lanPublic(), fx: { rate: 7.2, at: new Date().toISOString() }, + lanURLs: lan ? lanURLs : [], ...lanPublic(), ...(container().container ? { lanContainer: true } : {}), + ...(container().containerHost ? { lanContainerHost: container().containerHost } : {}), fx: { rate: 7.2, at: new Date().toISOString() }, ...(options.publicURL ? { gateway: "http://127.0.0.1:3999", ...publicURL() } : {}) }); const rows = [ { callerKeyId: "laptop", callerKeyName: "Laptop", in: 100, out: 10, cost: 0.1 }, @@ -64,13 +70,13 @@ function fixture(lang, theme, events, options = {}) { // gateway listens, as magpie's boot.js says it, and while shared the // addresses other machines use, MAGPIE_PUBLIC_URL with them ...(options.publicURL || options.bootGateway ? { sideGateway: { url: "http://127.0.0.1:3999", running: true, boot: true, - ...(lan ? { lan, lanURLs } : {}), ...publicURL() } } : {}) })};` }); + ...(lan ? { lan, lanURLs } : {}), ...container(), ...publicURL() } } : {}) })};` }); if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); if (url.pathname === "/favicon.ico") return route.fulfill({ status: 204 }); if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme } }); if (url.pathname === "/api/providers") return json({ providers: [{ id: "relay", name: "Relay", icon: "generic", models: [{ id: "m", name: "Model", on: true }], agents: [] }], - gateway: { running: true, window: true, mine: true, url: "http://127.0.0.1:3999", lan, lanURLs: lan ? lanURLs : [], ...lanPublic(), ...publicURL(), calls: [], groups: [] }, + gateway: { running: true, window: true, mine: true, url: "http://127.0.0.1:3999", lan, lanURLs: lan ? lanURLs : [], ...lanPublic(), ...container(), ...publicURL(), calls: [], groups: [] }, }); if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); if (url.pathname === "/api/settings/lan") { diff --git a/internal/gui/tests/lan-docker.test.cjs b/internal/gui/tests/lan-docker.test.cjs index 43876c056..e936701bb 100644 --- a/internal/gui/tests/lan-docker.test.cjs +++ b/internal/gui/tests/lan-docker.test.cjs @@ -1,19 +1,27 @@ // Run with Node's test runner and Playwright on the module path; see README.md. // Share on local network in a container (莫 on Discord: magpie in Docker on -// a NAS showed the container's own 172.17.x address): the addresses magpie -// finds for itself there are the container's, which other devices can't -// reach. Served over the network (magpie web), the page offers the host it -// was opened at, on the gateway's port, and says so; opened at localhost it -// keeps the container's addresses but says they are the container's own -// and to set MAGPIE_PUBLIC_URL. Outside a container nothing changes. The -// OpenAI/Anthropic switch keeps the host and moves nothing. English and -// Chinese, Chromium and WebKit; no backend, the API is faked here. +// a NAS showed the container's own 172.17.x address; jiezhengj on Discord: +// other devices used the host's 192.168.31.218:3425 well, and other +// containers on the NAS needed the host's Docker bridge address, +// http://172.17.0.1:3425): the addresses magpie finds for itself there are +// the container's, which neither reach. Served over the network (magpie +// web), the page offers the host it was opened at first, on the gateway's +// port, and after it the host's bridge address, named other containers'; +// opened at localhost it offers the bridge address and says the host's +// own is MAGPIE_PUBLIC_URL's. With no default route known it keeps the +// container's addresses, said to be its own. Outside a container nothing +// changes. The OpenAI/Anthropic switch keeps the host and moves nothing. +// The Gateway page's list, the key page's address and the sidebar's line +// say the same, whether Share on local network is on or not (the image's +// MAGPIE_ADDR puts the gateway on the network either way). 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 { watchSettingsReads, settingsDrawn } = require("./reader.cjs"); +const { fixture } = require("./fixtures/caller-keys.cjs"); const assets = path.resolve(__dirname, "../assets"); @@ -54,15 +62,23 @@ function server(lang, web, over) { const words = { en: { container: "In a container", - opened: "Where this page was opened, on the gateway’s port; MAGPIE_PUBLIC_URL sets another", + opened: "Other devices use the host’s address this page was opened at, and other containers on this host the host’s Docker bridge address, both on the gateway’s port; MAGPIE_PUBLIC_URL sets another", + bridge: "Other containers on this host use the host’s Docker bridge address, on the gateway’s port; other devices use the host’s own, which MAGPIE_PUBLIC_URL puts here", own: "The container’s own addresses, which other devices can’t reach: set MAGPIE_PUBLIC_URL to the host’s", + others: "Other containers on this host", lan: "Local network", }, zh: { container: "在容器中运行", - opened: "打开本页所用的地址,端口为网关端口;可用 MAGPIE_PUBLIC_URL 另设", + opened: "其他设备用打开这个页面所用的宿主机地址,本机上的其他容器用宿主机的 Docker bridge 地址,端口都是网关的端口;MAGPIE_PUBLIC_URL 可另设", + bridge: "本机上的其他容器用宿主机的 Docker bridge 地址,端口是网关的端口;其他设备用宿主机自己的地址,用 MAGPIE_PUBLIC_URL 把它设在这里", own: "容器自身的地址,其他设备无法访问:请将 MAGPIE_PUBLIC_URL 设为宿主机地址", + others: "同一主机上的其他容器", lan: "局域网", }, + "zh-TW": { others: "同一主機上的其他容器", lan: "區域網" }, + ja: { others: "同じホストのほかのコンテナ", lan: "ローカルネットワーク" }, + de: { others: "Andere Container auf diesem Host", lan: "Lokales Netzwerk" }, }; +const BRIDGE = "http://172.17.0.1:3425"; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { test(engine + ": in a container, the share address is the host's, not the container's", async (t) => { @@ -88,10 +104,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await watchSettingsReads(page); await page.goto(at + "/?view=settings&tab=network"); await settingsDrawn(page); // rows found are the ones that stay (#1659) - await page.locator("#lanList .lan-address-text").waitFor(); + await page.locator("#lanList .lan-address-row").waitFor(); return { page, errors }; }; - const address = (page) => page.locator("#lanList .lan-address-text").textContent(); + const address = (page) => page.locator("#lanList .lan-address-text, #lanList .lan-interface .lan-url").textContent(); const note = (page) => page.locator("#lanList .lan-container"); for (const lang of ["en", "zh"]) { @@ -99,7 +115,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await t.test(lang, async () => { // magpie web, opened at the NAS's address: the gateway there { - const { page, errors } = await open(lang, "http://192.168.1.20:3430", true, { lanContainer: true }); + const { page, errors } = await open(lang, "http://192.168.1.20:3430", true, { lanContainer: true, lanContainerHost: BRIDGE }); assert.equal(await address(page), "http://192.168.1.20:3425/v1"); assert.equal((await note(page).locator(".name").textContent()).trim(), w.container); assert.equal((await note(page).locator(".sub").textContent()).trim(), w.opened); @@ -121,10 +137,26 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(await scroll(), before, "the switch moved the page"); const border = await note(page).evaluate((r) => getComputedStyle(r).borderLeftWidth); assert(border === "0px" || border === "", "no left border accent: " + border); + // the host's bridge address is offered after it, named other + // containers' (after the switch, so the menu's own scroll is not + // the switch's); the container's own is not offered + await page.locator("#lanList .lan-interface").click(); + const items = page.locator(".proto-menu .pm-item"); + assert.deepEqual((await items.locator(".pm-name").allTextContents()).map((x) => x.trim()), + ["http://192.168.1.20:3425", BRIDGE]); + assert.deepEqual((await items.locator(".pm-note").allTextContents()).map((x) => x.trim()), ["", w.others]); assert.deepEqual(errors, []); } - // opened at localhost (a tunnel, or on the NAS itself): the - // container's address stays, said to be the container's own + // opened at localhost (a tunnel, or on the NAS itself): the host's + // bridge address, for other containers, and the host's own is + // MAGPIE_PUBLIC_URL's + { + const { page, errors } = await open(lang, "http://localhost:3430", true, { lanContainer: true, lanContainerHost: BRIDGE }); + assert.equal(await address(page), BRIDGE + "/v1"); + assert.equal((await note(page).locator(".sub").textContent()).trim(), w.bridge); + assert.deepEqual(errors, []); + } + // no default route known: the container's own, said to be its own { const { page, errors } = await open(lang, "http://localhost:3430", true, { lanContainer: true }); assert.equal(await address(page), "http://172.17.0.2:3425/v1"); @@ -142,3 +174,66 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", } }); } + +// The Gateway page, the key page and the sidebar read the gateway's own +// flags, not Settings': in Docker, Share on local network is off and the +// gateway is on the network all the same (jiezhengj: other containers on +// the NAS needed the host's bridge address). +const OWN = "http://172.17.0.2:3999", HOSTBR = "http://172.17.0.1:3999"; +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine} ${lang}: in a container, Gateway and the sidebar name the host's address first`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const w = words[lang]; + const open = async (at, container, containerHost) => { + const page = await (await browser.newContext({ viewport: { width: 1100, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, "light", [], { lan: true, web: true, container, containerHost, lanURLs: [OWN], bootGateway: true })); + await page.goto(at + "/?view=gateway"); + await page.locator("#gatewayLan .gw-url").first().waitFor(); + await page.waitForFunction(() => document.querySelector("#gatewayKeys .gw-key-page code")); + return { page, errors }; + }; + const list = async (page) => { + const rows = page.locator("#gatewayLan .gw-url"); + const out = []; + for (let i = 0; i < await rows.count(); i++) + out.push([(await rows.nth(i).locator(".gw-url-label").textContent()).trim(), (await rows.nth(i).locator("code").textContent()).trim()]); + return out; + }; + const side = (page) => page.locator("#sideGw span").textContent(); + const keyPage = (page) => page.locator("#gatewayKeys .gw-key-page code").textContent(); + + // opened at the NAS's address: the host's first, the host's bridge + // address after it as other containers'; the sidebar and the key + // page name the host's + { + const { page, errors } = await open("http://192.168.31.218:3430", true, HOSTBR); + assert.deepEqual((await list(page)).slice(1), [[w.lan, "http://192.168.31.218:3999"], [w.others, HOSTBR]]); + assert.match(await side(page), /192\.168\.31\.218:3999/); + assert.equal(await keyPage(page), "http://192.168.31.218:3999/me"); + assert.deepEqual(errors, []); + } + // opened at localhost: the bridge address, as other containers', and + // never the container's own as the local network's + { + const { page, errors } = await open("http://localhost:3430", true, HOSTBR); + assert.deepEqual((await list(page)).slice(1), [[w.others, HOSTBR]]); + assert.match(await side(page), /172\.17\.0\.1:3999/); + assert.deepEqual(errors, []); + } + // not in a container: as it was + { + const { page, errors } = await open("http://192.168.31.218:3430", false); + assert.deepEqual((await list(page)).slice(1), [[w.lan, OWN]]); + assert.match(await side(page), /172\.17\.0\.2:3999/); + assert.equal(await keyPage(page), OWN + "/me"); + assert.deepEqual(errors, []); + } + }); + } +} diff --git a/site/public/docs/docker.html b/site/public/docs/docker.html index 445f75f32..5a4e4d779 100644 --- a/site/public/docs/docker.html +++ b/site/public/docs/docker.html @@ -119,6 +119,7 @@ docker logs magpie
● magpie web on http://127.0.0.1:3430/?k=0f3c9a1e…
   on the network http://172.17.0.2:3430/?k=0f3c9a1e…
   these are the container's own addresses: other machines use the host's, and MAGPIE_PUBLIC_URL=http://<host>:<port> puts it here
+  other containers on this host http://172.17.0.1:3425
 ! anyone with the link can change magpie and see its keys, and the network carries it unencrypted
   the link carries MAGPIE_WEB_KEY · gateway http://127.0.0.1:3425 · Ctrl-C to stop
@@ -176,6 +177,7 @@ docker logs magpie
  • Publish the portRecreate the container with -p 3425:3425, or bound to the NAS’s LAN or VPN address (-p 192.168.1.20:3425:3425), and with -e MAGPIE_PUBLIC_URL=http://192.168.1.20:3425.
  • On each other computer, point the agent at the gateway with one of those keys as its API key: http://192.168.1.20:3425/v1 for an OpenAI client, http://192.168.1.20:3425 for an Anthropic or Gemini one. Model ids are provider/model, or a routing group’s; GET /v1/models lists them. If that computer runs magpie itself, add the container as a Remote magpie instead, and magpie wires its agents for you.

    +

    Other containers on the same host. Another container on the NAS reaches magpie at the host, through the Docker bridge’s gateway and the published port: http://172.17.0.1:3425 on Docker’s default bridge. The container’s own 172.17.x address is no use to it, and the host’s LAN address may not be either, as a NAS’s firewall can keep containers from it. host.docker.internal is the same address on Docker Desktop, and on Linux only in a container given extra_hosts: ["host.docker.internal:host-gateway"]. A container on magpie’s own compose network, or one you made, can use its name, http://magpie:3425. Either way it sends a gateway key. The log and the browser UI list this address as Other containers on this host, after the host’s address the page was opened at.

    Settings → Network and sharing → Share on local network isn’t needed in the container: turning it on also makes a gateway key named Magpie, and the gateway asks for a key from outside the container either way.

    Upgrading from an earlier image. An agent outside the container that sends magpie, or any other key that isn’t an enabled gateway key, now gets 401 (“the API key sent is not an enabled magpie gateway key”). Make it a key as above and put that in the agent’s settings. Agents that already send a gateway key, and a Remote magpie set up with one, keep working.

    Allowed addresses. On a public host, set -e MAGPIE_ALLOW_IPS=203.0.113.7,10.0.0.0/8 to the addresses your clients come from. A request from any other address is refused 403 before its key is looked at, so a key that leaks is no use from elsewhere; the refusal names the address it came from, as does the container’s log. magpie judges the address of the connection itself, never an X-Forwarded-For header, and a mistyped entry lets nothing in rather than everything. Docker’s default bridge network passes a client’s own address into the container, but a request from the host itself arrives from the bridge’s gateway (172.17.0.1), and Docker Desktop and rootless Docker show every client as one address of their own: add that, or check what the 403 says. Behind a reverse proxy or tunnel, every request comes from the proxy’s address, so limit who reaches magpie at the proxy. On the desktop app the same list is Settings → Network and sharing → Allowed addresses.

    diff --git a/site/public/docs/ja/docker.html b/site/public/docs/ja/docker.html index 3ec2eb5dd..5a30641b9 100644 --- a/site/public/docs/ja/docker.html +++ b/site/public/docs/ja/docker.html @@ -119,6 +119,7 @@ docker logs magpie
    ● magpie web on http://127.0.0.1:3430/?k=0f3c9a1e…
       on the network http://172.17.0.2:3430/?k=0f3c9a1e…
       these are the container's own addresses: other machines use the host's, and MAGPIE_PUBLIC_URL=http://<host>:<port> puts it here
    +  other containers on this host http://172.17.0.1:3425
     ! anyone with the link can change magpie and see its keys, and the network carries it unencrypted
       the link carries MAGPIE_WEB_KEY · gateway http://127.0.0.1:3425 · Ctrl-C to stop
    @@ -176,6 +177,7 @@ docker logs magpie
  • ポートを公開する-p 3425:3425(または NAS の LAN や VPN のアドレスに限定して -p 192.168.1.20:3425:3425)と -e MAGPIE_PUBLIC_URL=http://192.168.1.20:3425 を付けてコンテナを作り直します。
  • ほかのコンピューターでは、エージェントをゲートウェイに向け、そのキーのどれかを API キーにします:OpenAI クライアントなら http://192.168.1.20:3425/v1、Anthropic や Gemini なら http://192.168.1.20:3425。モデル ID は provider/model かルーティンググループの名前で、GET /v1/models が一覧を返します。そのコンピューターでも magpie を動かしているなら、コンテナをリモート magpie として追加すれば、magpie がエージェントを設定します。

    +

    同じホストのほかのコンテナ。NAS 上のほかのコンテナは、Docker の bridge のゲートウェイと公開ポートを通して、ホスト上の magpie に到達します:Docker 既定の bridge では http://172.17.0.1:3425 です。コンテナ自身の 172.17.x アドレスはそのコンテナには使えず、ホストの LAN アドレスも、NAS のファイアウォールがコンテナからの接続を止めることがあるので、使えない場合があります。host.docker.internal は Docker Desktop では同じアドレスで、Linux では extra_hosts: ["host.docker.internal:host-gateway"] を付けたコンテナにだけあります。magpie と同じ compose ネットワークや自分で作ったネットワークのコンテナは、名前で到達できます:http://magpie:3425。どちらの場合もゲートウェイキーを送ります。ログとブラウザ UI は、このアドレスを 同じホストのほかのコンテナ として、ページを開いたホストのアドレスの後に表示します。

    コンテナでは 設定 → ネットワークと共有 → ローカルネットワークで共有 は不要です。オンにすると Magpie という名前のゲートウェイキーも作られますが、ゲートウェイはどちらでもコンテナの外からのリクエストにキーを求めます。

    以前のイメージからの更新。コンテナの外から magpie や、有効なゲートウェイキーではないキーを送るエージェントは、401(“the API key sent is not an enabled magpie gateway key”)を受け取るようになります。上の手順でキーを作り、エージェントの設定に入れてください。すでにゲートウェイキーを送っているエージェントや、ゲートウェイキーで追加したリモート magpie はそのまま動きます。

    許可するアドレス。公開ホストでは -e MAGPIE_ALLOW_IPS=203.0.113.7,10.0.0.0/8 にクライアントのアドレスを書きます。ほかのアドレスからのリクエストはキーを見る前に 403 で拒否されるので、漏れたキーもよそからは使えません。拒否のメッセージとコンテナのログには、リクエスト元のアドレスが出ます。magpie が見るのは接続そのもののアドレスで、X-Forwarded-For ヘッダーは信用しません。書き間違えた項目は、すべてを通すのではなく、何も通しません。Docker 既定の bridge ネットワークはクライアント自身のアドレスをコンテナに渡しますが、ホスト自身からのリクエストは bridge のゲートウェイ(172.17.0.1)から届き、Docker Desktop や rootless Docker ではすべてのクライアントがそれ自身のひとつのアドレスに見えます。それを追加するか、403 に書かれたアドレスを確かめてください。リバースプロキシやトンネルの後ろでは、すべてのリクエストがプロキシのアドレスから届くので、接続できる人はプロキシで制限してください。デスクトップ版では同じリストが 設定 → ネットワークと共有 → 許可するアドレス にあります。

    diff --git a/site/public/docs/zh/docker.html b/site/public/docs/zh/docker.html index 7dbf184d5..b19365193 100644 --- a/site/public/docs/zh/docker.html +++ b/site/public/docs/zh/docker.html @@ -119,6 +119,7 @@ docker logs magpie
    ● magpie web on http://127.0.0.1:3430/?k=0f3c9a1e…
       on the network http://172.17.0.2:3430/?k=0f3c9a1e…
       these are the container's own addresses: other machines use the host's, and MAGPIE_PUBLIC_URL=http://<host>:<port> puts it here
    +  other containers on this host http://172.17.0.1:3425
     ! anyone with the link can change magpie and see its keys, and the network carries it unencrypted
       the link carries MAGPIE_WEB_KEY · gateway http://127.0.0.1:3425 · Ctrl-C to stop
    @@ -176,6 +177,7 @@ docker logs magpie
  • 发布端口用 -p 3425:3425(或绑定到 NAS 的局域网或 VPN 地址,-p 192.168.1.20:3425:3425)并加上 -e MAGPIE_PUBLIC_URL=http://192.168.1.20:3425 重新创建容器。
  • 在其他电脑上,把 Agent 指向这个网关,用其中一个密钥作为 API key:OpenAI 客户端用 http://192.168.1.20:3425/v1,Anthropic 或 Gemini 客户端用 http://192.168.1.20:3425。模型 id 是 provider/model 或路由组的名字,GET /v1/models 会列出它们。如果那台电脑自己也运行 magpie,就把容器添加为远程 magpie,由 magpie 替你配置 Agent。

    +

    同一宿主机上的其他容器。NAS 上的其他容器通过 Docker bridge 的网关和发布的端口访问宿主机上的 magpie:Docker 默认 bridge 网络上是 http://172.17.0.1:3425。容器自己的 172.17.x 地址对它们没用,宿主机的局域网地址也可能不行,因为 NAS 的防火墙可能挡住来自容器的访问。host.docker.internal 在 Docker Desktop 上是同一个地址,在 Linux 上只有加了 extra_hosts: ["host.docker.internal:host-gateway"] 的容器里才有。和 magpie 在同一个 compose 网络或你自己建的网络里的容器,可以按名字访问:http://magpie:3425。无论哪种都要带网关密钥。日志和 Web 界面把这个地址列为 同一主机上的其他容器,排在打开页面所用的宿主机地址之后。

    容器里不需要打开 设置 → 网络与共享 → 局域网共享:打开它会另外生成一个名为 Magpie 的网关密钥,而不论开关如何,网关都会向容器外的请求要密钥。

    从旧镜像升级。容器外发送 magpie 或其他非启用网关密钥的 Agent,现在会收到 401(“the API key sent is not an enabled magpie gateway key”)。按上面的步骤给它生成一个密钥,填进 Agent 的设置。已经发送网关密钥的 Agent,以及用网关密钥添加的远程 magpie,照常工作。

    允许的地址。在公网主机上,用 -e MAGPIE_ALLOW_IPS=203.0.113.7,10.0.0.0/8 写上你的客户端所在的地址。来自其他地址的请求在看密钥之前就被拒绝(403),所以泄露的密钥从别处也用不了;拒绝信息和容器日志都会写出请求来自的地址。magpie 判断的是连接本身的地址,从不采信 X-Forwarded-For 头;写错的条目不会放行任何地址,而不是放行所有地址。Docker 默认的 bridge 网络会把客户端自己的地址传进容器,但宿主机自己发出的请求来自 bridge 的网关(172.17.0.1),Docker Desktop 和 rootless Docker 则把所有客户端显示成它们自己的一个地址:把它加上,或看 403 里写的是哪个。在反向代理或隧道后面时,所有请求都来自代理的地址,请在代理那里限制谁能访问。桌面版里同一个列表在 设置 → 网络与共享 → 允许的地址。