gateway, gui, settings: an IP / CIDR allow list for the gateway, from MAGPIE_ALLOW_IPS or Settings beside Share on local network (lc on Discord)

What changed: lc runs magpie in Docker on a public host and asked that
only some addresses reach it at all. With a list set, a request from an
address outside it is refused 403 ("magpie answers only the addresses on
its allow list ..., and this request came from <addr>: add it there to
let it in") before its gateway key is looked at, so a leaked key is no use from
elsewhere. No list is as before.
- internal/settings/allowips.go: SplitAllowIPs, ParseAllowIP (an IP or a
  CIDR range, v4 or v6; zones dropped, v4-mapped unmapped), CleanAllowIPs.
  Settings gets AllowIPs (allowIPs).
- internal/gateway/allow.go: MAGPIE_ALLOW_IPS (comma or space separated)
  sets the list in place of Settings'. The address judged is the
  connection's own (r.RemoteAddr); X-Forwarded-For and the rest are never
  believed (magpie has no trusted-proxy list; MAGPIE_TRUST_PROXY never
  reads forwarding headers, and this follows it). Loopback and this
  computer's own interface addresses always pass. An entry that doesn't
  read lets nothing in and is logged once, so a typo never opens magpie
  to every address. lanGuard checks it after the OAuth callback and
  before the rebound-Host and key checks; `magpie web` is wrapped with
  AllowGuard too.
- GUI: Settings > Network shows an "Allowed addresses" row under Share on local
  network when sharing is on, the page is open from another computer, or
  the env var is set (then read-only, saying so). POST
  /api/settings/allowips saves it, refuses it while the env var is set,
  refuses an entry that doesn't read, and refuses a list that would shut
  out the address the page itself is open from (KeepsOut). The generic
  settings save keeps AllowIPs. Strings in zh, zh-TW, ja and de.
- Docs: the Docker page (en, zh, ja) lists MAGPIE_ALLOW_IPS with a note
  that a request from the host itself arrives from the bridge's gateway
  (172.17.0.1), that Docker Desktop and rootless Docker show clients as
  one address of their own, and that behind a proxy every request comes
  from the proxy; docs/reference.md and docs/subsystems/gateway-routing.md
  describe it. The READMEs list no env vars, so they are unchanged.

Why: a gateway key is the only lock on a public host; an allow list keeps
everyone else from even trying it.

Run (machine load average 75-140 from other sessions, so the large
packages ran in slices of their top-level tests, each slice
-timeout 9m, private GOCACHE, sandbox HOME):
- New tests: internal/gateway/allow_test.go TestAllowList (allowed,
  denied, CIDR v4/v6, IPv6 literal, link-local with zone, v4-mapped,
  loopback and own address always in, on the list still needs a key,
  a typo shuts everything out, env over settings), TestAllowListServed
  (a real connection from loopback passes lanGuard under a list naming
  nothing of this computer's; a request from elsewhere is 403 naming its
  address and MAGPIE_ALLOW_IPS), TestKeepsOut; internal/settings/allowips_test.go
  TestCleanAllowIPs; internal/gui/allowips_settings_test.go
  TestAllowIPsSetting; internal/gui/tests/allow-ips.test.cjs (14/14 in
  chromium and webkit, at a 390px panel, en and zh, keys in zh, zh-TW,
  ja and de). Broken by
  hand: with lanGuard's check removed TestAllowList and TestAllowListServed
  FAIL; with KeepsOut skipped TestAllowIPsSetting FAILs; with renderAllow
  not called the GUI test has 5 failures. Restored, all pass.
- internal/gui/settings_keep_test.go gains AllowIPs:
  TestSettingsSaveKeepsWhatItDoesNotSend failed without it, as it should
  for a new field.
- go test -tags nogui: every package ok. internal/gateway (4 slices),
  internal/agent (4), internal/provider (3), internal/gui (2),
  internal/plugin (2), the rest whole. GUI Network-settings test files
  (11) 98/98 and i18n-keys ok, both engines.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... ok; linux and windows builds ok.
- Not tried: a real Docker container on a public host (the bridge note
  is from Docker's docs, not checked here); behind a real reverse proxy.
This commit is contained in:
yetone
2026-10-12 23:21:41 +08:00
parent 77aabb9a46
commit 7a9490638d
19 changed files with 917 additions and 3 deletions
+11
View File
@@ -591,6 +591,17 @@ address with sharing on, not at loopback. A proxy here that signs its
clients in itself can be trusted with `MAGPIE_TRUST_PROXY=1`, which keeps
what it forwards local, as before.
To let other computers in only from some addresses, list them as IPs and
CIDR ranges in **Settings → Network and sharing → Allowed addresses**, or in
`MAGPIE_ALLOW_IPS` (`203.0.113.7,10.0.0.0/8,2001:db8::/32`), which comes
first. A request from any other address is refused 403, even with an
enabled gateway key, and the refusal names the address it came from. This
computer is always let in. The address is the connection's own, never a
forwarding header, so behind a proxy or tunnel every client has the proxy's
address: limit them at the proxy. A mistyped entry in `MAGPIE_ALLOW_IPS`
lets nothing in rather than everything. `magpie web`'s page honours the same
list.
**Usage → Overview → Gateway keys** groups calls by the client's key, never
the provider's credential. **Usage → Requests** offers the same filter;
CSV includes `caller_key_id` and `caller_key_name`. Deleted keys keep their
+1 -1
View File
@@ -16,7 +16,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
| Part | Responsibility | Source |
| --- | --- | --- |
| Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-<agent>` (`TokenFor`). `agentOf` tells which agent asked, first by token, then by User-Agent. | [`gateway.go`](../../internal/gateway/gateway.go) |
| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. `null` and other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost`, `*.localhost`, a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/<token>` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). | [`gateway.go`](../../internal/gateway/gateway.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) |
| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. `null` and other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost`, `*.localhost`, a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/<token>` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`; the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) |
| Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-<slug>`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) |
| Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) |
| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight` (`weightedFirst`). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/provider/routing.go`](../../internal/provider/routing.go) |
+179
View File
@@ -0,0 +1,179 @@
package gateway
import (
"log"
"net"
"net/http"
"net/netip"
"os"
"strings"
"sync"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// The allow list (lc on Discord, magpie in Docker on a public host): the
// addresses other computers may reach magpie from at all, as IPs and CIDR
// ranges. A request from any other address is refused 403 before its key
// is looked at, so a gateway key that leaks is of no use from elsewhere.
// No list lets every address in, as before. This computer (loopback, and
// the computer's own addresses) is always let in.
//
// The address judged is the connection's own (r.RemoteAddr). A forwarding
// header (X-Forwarded-For and the rest) is never taken for it: anyone can
// write one, and magpie keeps no list of proxies to believe. A proxy or
// tunnel on this computer reaches magpie from loopback, so what it passes
// on is let in here, and still needs a gateway key (proxied); limit who
// reaches such a proxy at the proxy.
// AllowIPsEnv names the environment variable that sets the list, in place
// of Settings' (for Docker and `magpie web`).
const AllowIPsEnv = "MAGPIE_ALLOW_IPS"
// AllowIPs is the allow list in force, as written, and whether
// MAGPIE_ALLOW_IPS set it. Empty: no list, every address let in.
func AllowIPs() (list []string, fromEnv bool) {
if v := strings.TrimSpace(os.Getenv(AllowIPsEnv)); v != "" {
return settings.SplitAllowIPs(v), true
}
return settings.Load().AllowIPs, false
}
var warnedAllow sync.Map
// allowPrefixes is the list in force, read; on says one is set. An entry
// that doesn't read (a mistyped MAGPIE_ALLOW_IPS) lets nothing in and is
// logged once: the list stays on, so a typo never opens magpie to every
// address.
func allowPrefixes() (ps []netip.Prefix, on bool) {
list, _ := AllowIPs()
for _, e := range list {
p, err := settings.ParseAllowIP(e)
if err != nil {
if _, done := warnedAllow.LoadOrStore(e, true); !done {
log.Printf("%s: %v; it lets no address in", AllowIPsEnv, err)
}
continue
}
ps = append(ps, p)
}
return ps, len(list) > 0
}
// peerAddr is the address r's connection came from; false when
// RemoteAddr holds none.
func peerAddr(r *http.Request) (netip.Addr, bool) {
if ap, err := netip.ParseAddrPort(r.RemoteAddr); err == nil {
return ap.Addr().WithZone("").Unmap(), true
}
h, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
h = r.RemoteAddr
}
a, err := netip.ParseAddr(strings.Trim(h, "[]"))
if err != nil {
return netip.Addr{}, false
}
return a.WithZone("").Unmap(), true
}
// ownAddr: a is one of this computer's own addresses, which a connection
// comes from only when it was made here (an agent calling the address
// MAGPIE_ADDR names, which isn't loopback).
var ownAddr = func(a netip.Addr) bool {
addrs, err := net.InterfaceAddrs()
if err != nil {
return false
}
for _, ia := range addrs {
if n, ok := ia.(*net.IPNet); ok {
if b, ok := netip.AddrFromSlice(n.IP); ok && b.Unmap() == a {
return true
}
}
}
return false
}
// AllowedFrom: a request from a may reach magpie under the allow list —
// there is none, a is this computer's, or a is in it.
func AllowedFrom(a netip.Addr) bool {
ps, on := allowPrefixes()
if !on || a.IsLoopback() {
return true
}
for _, p := range ps {
if p.Contains(a) {
return true
}
}
return ownAddr(a)
}
// allowedListFrom is AllowedFrom for a list not yet in force (Settings
// checking a new one won't shut out the page it was saved from).
func allowedListFrom(list []string, a netip.Addr) bool {
if len(list) == 0 || a.IsLoopback() {
return true
}
for _, e := range list {
if p, err := settings.ParseAllowIP(e); err == nil && p.Contains(a) {
return true
}
}
return ownAddr(a)
}
// KeepsOut: the allow list list would refuse r, a request that came in
// from elsewhere; it names r's address.
func KeepsOut(list []string, r *http.Request) (string, bool) {
a, ok := peerAddr(r)
if !ok {
return "", false
}
return a.String(), !allowedListFrom(list, a)
}
// allowed: r may reach magpie under the allow list; it names r's address
// when it may not.
func allowed(r *http.Request) (string, bool) {
if _, on := allowPrefixes(); !on {
return "", true
}
a, ok := peerAddr(r)
if !ok {
return r.RemoteAddr, false
}
return a.String(), AllowedFrom(a)
}
// notAllowed says why a request from addr was refused.
func notAllowed(addr string) string {
return "magpie answers only the addresses on its allow list (" + AllowIPsEnv + ", or Settings → Network and sharing → Allowed addresses), and this request came from " + addr + ": add it there to let it in"
}
// AllowGuard refuses a request from an address the allow list leaves out,
// 403, before anything else looks at it: the page `magpie web` serves.
func AllowGuard(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if addr, ok := allowed(r); !ok {
log.Printf("refused %s %s from %s: not on the allow list", r.Method, r.URL.Path, addr)
http.Error(w, notAllowed(addr), http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
// refuseNotAllowed answers a gateway request from an address the allow
// list leaves out, in the error shape agents show; true when it did.
func refuseNotAllowed(w http.ResponseWriter, r *http.Request) bool {
addr, ok := allowed(r)
if ok {
return false
}
log.Printf("refused %s %s from %s: not on the allow list", r.Method, r.URL.Path, addr)
writeError(w, provider.Chat, http.StatusForbidden, notAllowed(addr))
return true
}
+156
View File
@@ -0,0 +1,156 @@
package gateway
import (
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/settings"
)
// lc on Discord, magpie in Docker on a public host: with an allow list,
// a request from an address outside it is refused 403 even with an
// enabled gateway key, saying why; one inside it is judged by its key as
// before; loopback and this computer's own addresses are always let in.
// MAGPIE_ALLOW_IPS comes before Settings' list, and a typo in it keeps
// the list on. No list lets every address in.
func TestAllowList(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "0.0.0.0:3499")
t.Setenv(AllowIPsEnv, "")
secret, err := access.Update("add-key", access.Change{Name: "Laptop"})
if err != nil {
t.Fatal(err)
}
h := lanGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
call := func(from string, key string) (int, string) {
r := httptest.NewRequest("POST", "/v1/messages", nil)
r.RemoteAddr = from
if key != "" {
r.Header.Set("x-api-key", key)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Code, w.Body.String()
}
type want struct {
from string
key string
code int
}
check := func(name string, cases []want) {
t.Helper()
for _, c := range cases {
code, body := call(c.from, c.key)
if code != c.code {
t.Errorf("%s: from %s key %v: %d %s, want %d", name, c.from, c.key != "", code, body, c.code)
}
if code == http.StatusForbidden && !strings.Contains(body, "allow list") {
t.Errorf("%s: from %s refused without saying why: %s", name, c.from, body)
}
}
}
// no list: every address, with a key
check("no list", []want{
{"203.0.113.9:5000", secret, 200},
{"[2001:db8::9]:5000", secret, 200},
{"203.0.113.9:5000", "", 401},
})
s := settings.Load()
s.AllowIPs = []string{"198.51.100.7", "10.0.0.0/8", "2001:db8:1::/48"}
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
check("settings", []want{
{"198.51.100.7:5000", secret, 200},
{"198.51.100.7:5000", "", 401}, // on the list, still needs a key
{"198.51.100.8:5000", secret, 403},
{"10.20.30.40:5000", secret, 200},
{"11.0.0.1:5000", secret, 403},
{"[::ffff:10.1.2.3]:5000", secret, 200}, // IPv4 as IPv6
{"[2001:db8:1:ff::2]:5000", secret, 200},
{"[2001:db8:2::2]:5000", secret, 403},
{"[fe80::db8:dead:beef:1%en0]:5000", secret, 403},
{"127.0.0.1:5000", "", 200},
{"[::1]:5000", "", 200},
{"127.8.9.10:5000", "", 200},
{"garbage", secret, 403},
})
// the environment's list comes first
t.Setenv(AllowIPsEnv, "203.0.113.0/24, 2001:db8::5")
check("env", []want{
{"203.0.113.200:5000", secret, 200},
{"[2001:db8::5]:5000", secret, 200},
{"[2001:db8::6]:5000", secret, 403},
{"198.51.100.7:5000", secret, 403},
{"127.0.0.1:5000", "", 200},
})
if l, env := AllowIPs(); !env || len(l) != 2 {
t.Errorf("AllowIPs = %v %v", l, env)
}
// a typo lets nothing in, and never opens magpie to all
t.Setenv(AllowIPsEnv, "203.0.113.0/33")
check("typo", []want{
{"203.0.113.9:5000", secret, 403},
{"198.51.100.7:5000", secret, 403},
{"127.0.0.1:5000", "", 200},
})
// this computer's own address (MAGPIE_ADDR on one interface's) is it
if a := ownIPv4(); a != "" {
check("own", []want{{net.JoinHostPort(a, "5000"), secret, 200}})
}
}
// On the running gateway, a real connection from loopback passes under a
// list that names nothing of this computer's, and the allow list is
// judged before the key: the refusal says so, not that the key is wrong.
func TestAllowListServed(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "0.0.0.0:3499")
t.Setenv(AllowIPsEnv, "192.0.2.1")
srv := httptest.NewServer(lanGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "in") })))
t.Cleanup(srv.Close)
res, err := http.Get(srv.URL + "/v1/models")
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode != 200 || string(b) != "in" {
t.Fatalf("loopback: %d %s", res.StatusCode, b)
}
// the same guard, a request from elsewhere with no key
r := httptest.NewRequest("GET", "/v1/models", nil)
r.RemoteAddr = "198.51.100.1:443"
w := httptest.NewRecorder()
lanGuard(http.NotFoundHandler()).ServeHTTP(w, r)
if w.Code != 403 || !strings.Contains(w.Body.String(), "198.51.100.1") || !strings.Contains(w.Body.String(), AllowIPsEnv) {
t.Errorf("elsewhere: %d %s", w.Code, w.Body.String())
}
}
// Settings checking a new list won't shut out the page it is saved from.
func TestKeepsOut(t *testing.T) {
r := httptest.NewRequest("POST", "/api/settings/allowips", nil)
r.RemoteAddr = "198.51.100.7:5000"
if a, out := KeepsOut([]string{"10.0.0.0/8"}, r); !out || a != "198.51.100.7" {
t.Errorf("leaves out: %v %q", out, a)
}
if _, out := KeepsOut([]string{"198.51.100.0/24"}, r); out {
t.Error("on the list")
}
if _, out := KeepsOut(nil, r); out {
t.Error("no list")
}
r.RemoteAddr = "127.0.0.1:5000"
if _, out := KeepsOut([]string{"10.0.0.0/8"}, r); out {
t.Error("loopback")
}
}
+7 -1
View File
@@ -227,7 +227,8 @@ func (s *Server) Relisten() error {
return nil
}
// lanGuard: a request from another machine — any peer that isn't
// lanGuard: a request from an address the allow list (allow.go) leaves out
// is refused first, whatever key it carries. A request from another machine — any peer that isn't
// loopback, and a proxy's or tunnel's on loopback — needs an enabled gateway
// key, and is answered at all only while the gateway is shared or listens on
// the network (OnNetwork). Loopback clients may still use any token,
@@ -238,6 +239,11 @@ func lanGuard(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
return
}
// the allow list comes before the key: one that leaked is of no
// use from an address left out of it
if refuseNotAllowed(w, r) {
return
}
remote := !local(r)
if !remote && rebound(r) {
log.Printf("refused %s %s: a web page reached loopback under the name %q", r.Method, r.URL.Path, r.Host)
+65
View File
@@ -0,0 +1,65 @@
package gui
import (
"net/http"
"net/http/httptest"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/settings"
)
// The allow list (lc on Discord) is saved cleaned; an entry that isn't an
// address, a list that would shut out the page saving it, and any list
// while MAGPIE_ALLOW_IPS sets it are refused with the list left as it
// was; a save of the rest of the Settings page leaves it alone; the page
// is told what the variable sets.
func TestAllowIPsSetting(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv(gateway.AllowIPsEnv, "")
srv := Handler(nil, nil)
post := func(path, body, from string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
r := httptest.NewRequest("POST", path, strings.NewReader(body))
r.RemoteAddr = from
srv.ServeHTTP(rec, r)
return rec
}
here := "127.0.0.1:50000"
rec := post("/api/settings/allowips", `{"ips":[" 203.0.113.7 ","10.1.2.3/8","2001:DB8::/32","203.0.113.7/32"]}`, here)
want := []string{"203.0.113.7", "10.0.0.0/8", "2001:db8::/32"}
if rec.Code != http.StatusOK || !slices.Equal(settings.Load().AllowIPs, want) || !strings.Contains(rec.Body.String(), `"allowIPs":["203.0.113.7","10.0.0.0/8","2001:db8::/32"]`) {
t.Fatalf("%d %s, saved %v", rec.Code, rec.Body, settings.Load().AllowIPs)
}
if rec := post("/api/settings/allowips", `{"ips":["my-laptop"]}`, here); rec.Code == http.StatusOK || !strings.Contains(rec.Body.String(), "is not an IP address") || !slices.Equal(settings.Load().AllowIPs, want) {
t.Errorf("not an address: %d %s, saved %v", rec.Code, rec.Body, settings.Load().AllowIPs)
}
// magpie web opened from 203.0.113.7: a list without it would shut it out
if rec := post("/api/settings/allowips", `{"ips":["10.0.0.0/8"]}`, "203.0.113.7:50000"); rec.Code == http.StatusOK || !strings.Contains(rec.Body.String(), "shut out 203.0.113.7") || !slices.Equal(settings.Load().AllowIPs, want) {
t.Errorf("shut out: %d %s, saved %v", rec.Code, rec.Body, settings.Load().AllowIPs)
}
if rec := post("/api/settings", `{"theme":"dark","lang":"en"}`, here); rec.Code != http.StatusOK || !slices.Equal(settings.Load().AllowIPs, want) {
t.Fatalf("the Settings page's save changed the list: %d %v", rec.Code, settings.Load().AllowIPs)
}
t.Setenv(gateway.AllowIPsEnv, "1.2.3.4, 10.0.0.0/8")
if rec := post("/api/settings/allowips", `{"ips":[]}`, here); rec.Code == http.StatusOK || !strings.Contains(rec.Body.String(), "MAGPIE_ALLOW_IPS") || !slices.Equal(settings.Load().AllowIPs, want) {
t.Errorf("under the variable: %d %s, saved %v", rec.Code, rec.Body, settings.Load().AllowIPs)
}
st := settingsState()
if st.AllowIPsEnv != "1.2.3.4, 10.0.0.0/8" || !slices.Equal(st.AllowIPsFromEnv, []string{"1.2.3.4", "10.0.0.0/8"}) {
t.Errorf("state: %q %v", st.AllowIPsEnv, st.AllowIPsFromEnv)
}
t.Setenv(gateway.AllowIPsEnv, "")
if rec := post("/api/settings/allowips", `{"ips":[]}`, here); rec.Code != http.StatusOK || len(settings.Load().AllowIPs) != 0 {
t.Fatalf("emptied: %d %v", rec.Code, settings.Load().AllowIPs)
}
}
+43
View File
@@ -346,6 +346,12 @@ type settingsJSON struct {
PublicURL string `json:"publicURL,omitempty"`
// MAGPIE_ADDR, when it sets the gateway's address over Settings' port
AddrEnv string `json:"addrEnv,omitempty"`
// MAGPIE_ALLOW_IPS, when it sets the allow list over Settings', and
// the list it sets; OnNetwork: MAGPIE_ADDR listens on the network, so
// the list is shown even while sharing is off
AllowIPsEnv string `json:"allowIPsEnv,omitempty"`
AllowIPsFromEnv []string `json:"allowIPsFromEnv,omitempty"`
OnNetwork bool `json:"onNetwork,omitempty"`
// Dir is the data folder beside a portable magpie (#508)
Portable bool `json:"portable,omitempty"`
// WSL is whether there is WSL to look in for agents (Windows), for
@@ -519,6 +525,10 @@ func searchState(s *settingsJSON) {
func settingsState() settingsJSON {
s := settingsJSON{Settings: settings.Load(), Version: Version, Dir: tilde(settings.Dir()), Portable: settings.Portable() != "", Gateway: gateway.URL()}
s.AddrEnv = os.Getenv("MAGPIE_ADDR")
s.OnNetwork = gateway.OnNetwork()
if list, env := gateway.AllowIPs(); env {
s.AllowIPsEnv, s.AllowIPsFromEnv = os.Getenv(gateway.AllowIPsEnv), list
}
if s.LAN || gateway.OnNetwork() {
s.PublicURL = gateway.PublicURL()
}
@@ -1073,6 +1083,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
in.LANKeyID = cur.LANKeyID
in.Port = cur.Port // set on its own (port below), which moves the gateway
in.CORSOrigins = cur.CORSOrigins // set on its own (cors below)
in.AllowIPs = cur.AllowIPs // set on its own (allowips below)
in.GitHubToken = cur.GitHubToken // set on its own (github-token below), never sent to the page
in.RequestArchive = cur.RequestArchive // the Gateway page's, set on its own
in.RequestArchiveMaxMB = cur.RequestArchiveMaxMB // in settings.json only
@@ -1661,6 +1672,38 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
}
writeJSON(rw, settingsState())
})
// the allow list (lc on Discord): the addresses other computers may
// reach magpie from, as IPs and CIDR ranges; none lets every address in.
// One that would shut out the page saving it (magpie web, opened from
// another computer) is refused, and so is any while MAGPIE_ALLOW_IPS
// sets the list.
mux.HandleFunc("POST /api/settings/allowips", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ IPs []string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
if _, env := gateway.AllowIPs(); env {
fail(rw, fmt.Errorf("%s sets the allow list; change it there", gateway.AllowIPsEnv))
return
}
list, err := settings.CleanAllowIPs(in.IPs)
if err != nil {
fail(rw, err)
return
}
if addr, out := gateway.KeepsOut(list, r); out {
fail(rw, fmt.Errorf("that allow list would shut out %s, the address this page is open from: add it first", addr))
return
}
s := settings.Load()
s.AllowIPs = list
if err := settings.Save(s); err != nil {
fail(rw, err)
return
}
writeJSON(rw, settingsState())
})
// the gateway's port (Magic_zero on Discord), set on its own: it moves
// the gateway and every agent connected to it
mux.HandleFunc("POST /api/settings/port", func(rw http.ResponseWriter, r *http.Request) {
+64
View File
@@ -20563,6 +20563,7 @@ function renderSettings() {
renderOTel(s, keep);
renderPort(s);
renderLAN(s);
renderAllow(s);
renderCORS(s);
renderSync();
@@ -22399,6 +22400,69 @@ function renderCORS(s) {
}
}
// renderAllow: the addresses other computers may reach magpie from at
// all (lc on Discord: magpie in Docker on a public host), as IPs and CIDR
// ranges, under Share on local network — a row to add one, and one row
// each to take it away. None listed lets every address in, with a gateway
// key, as before; this computer is always let in. MAGPIE_ALLOW_IPS, where
// set, is the list, shown and not edited here.
let allowDraft = { value: "", err: "" };
function allowSays(m) {
if (/is not an IP address/.test(m)) return t("Write an address as 203.0.113.7, or a range as 10.0.0.0/8 or 2001:db8::/32");
if (/shut out/.test(m)) return t("That list leaves out the address this page is open from: add it first, or this page can’t reach magpie");
if (/MAGPIE_ALLOW_IPS/.test(m)) return t("MAGPIE_ALLOW_IPS sets this list; change it there");
return t(m);
}
function renderAllow(s) {
const box = $("#allowList");
box.replaceChildren();
const env = s.allowIPsEnv || "";
if (!s.lan && !s.onNetwork && !env) return;
const list = env ? (s.allowIPsFromEnv || []) : (s.allowIPs || []);
const d = allowDraft;
const set = (next, done) => writingPrefs(api("settings/allowips", { ips: next }))
.then((ns) => { prefs = ns; d.err = ""; done?.(); renderSettings(); status(t("Saved"), "ok", 1500); })
.catch((e) => { d.err = allowSays(e.message); status(d.err, "err"); renderSettings(); });
const r = el("div", "row pref rule-row");
const who = el("div", "who");
const sub = d.err || (env ? t("Set by MAGPIE_ALLOW_IPS. Other computers reach magpie only from these addresses, even with a gateway key; this computer always can")
: t("Other computers reach magpie only from these addresses or ranges (CIDR), even with a gateway key; this computer always can. None listed lets every address in"));
who.append(el("div", "name", t("Allowed addresses")), el("div", "sub" + (d.err ? " err" : ""), sub));
r.append(who);
if (!env) {
const field = input(d.value, "203.0.113.7, 10.0.0.0/8");
field.className = "words rule-match allow-ip";
field.setAttribute("aria-label", t("IP address or range"));
field.autocomplete = "off";
field.spellcheck = false;
const add = el("button", "text", t("Add"));
add.onclick = () => {
d.value = field.value.trim();
if (!d.value) return field.focus();
set([...list, ...d.value.split(/[\s,;]+/).filter(Boolean)], () => { allowDraft = { value: "", err: "" }; });
};
field.oninput = () => { d.value = field.value; };
field.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") add.onclick(); };
const val = el("div", "val rule-add");
val.append(field, add);
r.append(val);
}
box.append(r);
for (const a of list) {
const row = el("div", "row pref allow-ip-row");
const w = el("div", "who");
w.append(el("div", "name", a));
const v = el("div", "val");
if (!env) {
const x = el("button", "text", t("Remove"));
x.onclick = () => set(list.filter((o) => o !== a));
v.append(x);
}
row.append(w, v);
box.append(row);
}
}
// renderLAN: the gateway shared on the local network, for agents on other
// machines. Gateway keys and connection examples live together in Gateway.
let lanSelectedURL = "", lanProtocol = "openai";
+28
View File
@@ -1881,6 +1881,13 @@ const I18N = {
"Web pages": "网页",
"Web page origin": "网页来源",
"Web pages that may call magpie": "允许调用 magpie 的网页",
"Allowed addresses": "允许的地址",
"IP address or range": "IP 地址或网段",
"Set by MAGPIE_ALLOW_IPS. Other computers reach magpie only from these addresses, even with a gateway key; this computer always can": "由 MAGPIE_ALLOW_IPS 设置。其他电脑只能从这些地址访问 magpie,即使带着网关密钥也一样;本机始终可以",
"Other computers reach magpie only from these addresses or ranges (CIDR), even with a gateway key; this computer always can. None listed lets every address in": "其他电脑只能从这些地址或网段(CIDR)访问 magpie,即使带着网关密钥也一样;本机始终可以。一个都不填则所有地址都可访问",
"Write an address as 203.0.113.7, or a range as 10.0.0.0/8 or 2001:db8::/32": "地址写成 203.0.113.7,网段写成 10.0.0.0/8 或 2001:db8::/32",
"That list leaves out the address this page is open from: add it first, or this page can’t reach magpie": "这个列表不含当前打开此页面的地址:请先把它加进去,否则此页面将无法访问 magpie",
"MAGPIE_ALLOW_IPS sets this list; change it there": "此列表由 MAGPIE_ALLOW_IPS 设置,请在那里修改",
"Scripts on these origins can call the gateway from a browser, each request with a gateway key from Gateway. A page from any other site is refused; pages on this computer are not": "这些来源的网页脚本可以在浏览器中调用网关,每个请求需带上「网关」页的网关密钥。其他网站的网页会被拒绝,本机的网页不受影响",
"Name each origin: a wildcard would let every web page use magpie": "请逐个填写来源:通配符会让任何网页都能使用 magpie",
"Write an origin as http://localhost:3000 or https://app.example.com": "来源格式如 http://localhost:3000 或 https://app.example.com",
@@ -6309,6 +6316,13 @@ const I18N = {
"Web pages": "網頁",
"Web page origin": "網頁來源",
"Web pages that may call magpie": "允許呼叫 magpie 的網頁",
"Allowed addresses": "允許的位址",
"IP address or range": "IP 位址或網段",
"Set by MAGPIE_ALLOW_IPS. Other computers reach magpie only from these addresses, even with a gateway key; this computer always can": "由 MAGPIE_ALLOW_IPS 設定。其他電腦只能從這些位址連到 magpie,即使帶著閘道金鑰也一樣;本機一律可以",
"Other computers reach magpie only from these addresses or ranges (CIDR), even with a gateway key; this computer always can. None listed lets every address in": "其他電腦只能從這些位址或網段(CIDR)連到 magpie,即使帶著閘道金鑰也一樣;本機一律可以。一個都不填則所有位址都可連線",
"Write an address as 203.0.113.7, or a range as 10.0.0.0/8 or 2001:db8::/32": "位址寫成 203.0.113.7,網段寫成 10.0.0.0/8 或 2001:db8::/32",
"That list leaves out the address this page is open from: add it first, or this page can’t reach magpie": "這個清單不含目前開啟此頁面的位址:請先把它加進去,否則此頁面將無法連到 magpie",
"MAGPIE_ALLOW_IPS sets this list; change it there": "此清單由 MAGPIE_ALLOW_IPS 設定,請在那裡修改",
"Scripts on these origins can call the gateway from a browser, each request with a gateway key from Gateway. A page from any other site is refused; pages on this computer are not": "這些來源的網頁尾本可以在瀏覽器中呼叫閘道,每個請求需帶上「閘道」頁的閘道金鑰。其他網站的網頁會被拒絕,本機的網頁不受影響",
"Name each origin: a wildcard would let every web page use magpie": "請逐個填寫來源:萬用字元會讓任何網頁都能使用 magpie",
"Write an origin as http://localhost:3000 or https://app.example.com": "來源格式如 http://localhost:3000 或 https://app.example.com",
@@ -10715,6 +10729,13 @@ const I18N = {
"Web pages": "Web ページ",
"Web page origin": "Web ページのオリジン",
"Web pages that may call magpie": "magpie を呼び出せる Web ページ",
"Allowed addresses": "許可するアドレス",
"IP address or range": "IP アドレスまたは範囲",
"Set by MAGPIE_ALLOW_IPS. Other computers reach magpie only from these addresses, even with a gateway key; this computer always can": "MAGPIE_ALLOW_IPS で設定されています。ほかのコンピュータは、ゲートウェイキーがあっても、これらのアドレスからしか magpie に接続できません。このコンピュータは常に接続できます",
"Other computers reach magpie only from these addresses or ranges (CIDR), even with a gateway key; this computer always can. None listed lets every address in": "ほかのコンピュータは、ゲートウェイキーがあっても、これらのアドレスまたは範囲(CIDR)からしか magpie に接続できません。このコンピュータは常に接続できます。何も登録しなければ、すべてのアドレスから接続できます",
"Write an address as 203.0.113.7, or a range as 10.0.0.0/8 or 2001:db8::/32": "アドレスは 203.0.113.7、範囲は 10.0.0.0/8 や 2001:db8::/32 のように書いてください",
"That list leaves out the address this page is open from: add it first, or this page can’t reach magpie": "このリストには、このページを開いているアドレスが含まれていません。先に追加しないと、このページから magpie に接続できなくなります",
"MAGPIE_ALLOW_IPS sets this list; change it there": "このリストは MAGPIE_ALLOW_IPS で設定されています。そちらで変更してください",
"Scripts on these origins can call the gateway from a browser, each request with a gateway key from Gateway. A page from any other site is refused; pages on this computer are not": "これらのオリジンのスクリプトはブラウザからゲートウェイを呼び出せます。各リクエストには「ゲートウェイ」ページのゲートウェイキーが必要です。ほかのサイトのページは拒否されます(このコンピューター上のページは除く)",
"Name each origin: a wildcard would let every web page use magpie": "オリジンは一つずつ指定してください。ワイルドカードではどの Web ページでも magpie を使えてしまいます",
"Write an origin as http://localhost:3000 or https://app.example.com": "オリジンは http://localhost:3000 や https://app.example.com の形式で入力してください",
@@ -15140,6 +15161,13 @@ const I18N = {
"Web pages": "Webseiten",
"Web page origin": "Herkunft der Webseite",
"Web pages that may call magpie": "Webseiten, die magpie aufrufen dürfen",
"Allowed addresses": "Erlaubte Adressen",
"IP address or range": "IP-Adresse oder Bereich",
"Set by MAGPIE_ALLOW_IPS. Other computers reach magpie only from these addresses, even with a gateway key; this computer always can": "Von MAGPIE_ALLOW_IPS festgelegt. Andere Computer erreichen magpie nur von diesen Adressen aus, auch mit einem Gateway-Schlüssel; dieser Computer immer",
"Other computers reach magpie only from these addresses or ranges (CIDR), even with a gateway key; this computer always can. None listed lets every address in": "Andere Computer erreichen magpie nur von diesen Adressen oder Bereichen (CIDR) aus, auch mit einem Gateway-Schlüssel; dieser Computer immer. Ist keine eingetragen, ist jede Adresse erlaubt",
"Write an address as 203.0.113.7, or a range as 10.0.0.0/8 or 2001:db8::/32": "Schreibe eine Adresse als 203.0.113.7 oder einen Bereich als 10.0.0.0/8 oder 2001:db8::/32",
"That list leaves out the address this page is open from: add it first, or this page can’t reach magpie": "Diese Liste lässt die Adresse aus, von der diese Seite geöffnet ist: Füge sie zuerst hinzu, sonst erreicht diese Seite magpie nicht mehr",
"MAGPIE_ALLOW_IPS sets this list; change it there": "MAGPIE_ALLOW_IPS legt diese Liste fest; ändere sie dort",
"Scripts on these origins can call the gateway from a browser, each request with a gateway key from Gateway. A page from any other site is refused; pages on this computer are not": "Skripte dieser Herkünfte können das Gateway aus dem Browser aufrufen, jede Anfrage mit einem Gateway-Schlüssel aus „Gateway“. Seiten anderer Websites werden abgewiesen, Seiten auf diesem Computer nicht",
"Name each origin: a wildcard would let every web page use magpie": "Jede Herkunft einzeln angeben: Ein Platzhalter ließe jede Webseite magpie nutzen",
"Write an origin as http://localhost:3000 or https://app.example.com": "Eine Herkunft wird wie http://localhost:3000 oder https://app.example.com geschrieben",
+1
View File
@@ -489,6 +489,7 @@
<div class="list prefs" id="portList"></div>
<div class="row-head"><span class="label" data-t>Local network</span></div>
<div class="list prefs" id="lanList"></div>
<div class="list prefs" id="allowList"></div>
<div class="row-head"><span class="label" data-t>Web pages</span></div>
<div class="list prefs" id="corsList"></div>
</section>
+1
View File
@@ -134,6 +134,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
LANKeyID: "lan-key-id",
Port: 3591,
CORSOrigins: []string{"http://localhost:3000"},
AllowIPs: []string{"203.0.113.7"},
GitHubToken: "ghp_kept",
RequestArchive: true,
RequestArchiveMaxMB: 64,
+256
View File
@@ -0,0 +1,256 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Allowed addresses (lc on Discord: magpie in Docker on a public host):
// Settings › Network, under Share on local network, lists the IPs and CIDR
// ranges other computers may reach magpie from at all. Shown while magpie
// is shared or listens on the network, not otherwise. One is added from a
// field and its Add button (or Enter), saved as the gateway cleaned it,
// and taken away with its Remove; one that isn't an address, and a list
// that would shut out the page saving it, are refused in the page's
// language and nothing is saved. Set by MAGPIE_ALLOW_IPS, the list is
// shown with no field and no Remove. At a 390px panel every row fits, and
// no click moves the page. English and Chinese, Chromium and WebKit, the
// strings in all four languages; 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 assets = path.resolve(__dirname, "../assets");
function settingsPayload(over) {
return {
theme: "light", lang: "en", tray: "panel", quotaLeft: false, currency: "usd",
dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [],
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false,
trayUsage: "", trayUsageEvery: 3, vision: "", imageGen: "",
version: "0.1.400", dir: "/config/magpie", gateway: "http://127.0.0.1:3425",
proxyNow: "none", proxySource: "none", login: false,
visionModels: [], imageGenModels: [], workbuddyCheckins: [],
lan: true, lanURLs: ["http://192.168.1.20:3425"],
fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
...over,
};
}
// what the gateway does with a list (internal/settings/allowips.go and
// gui/api.go), for the few forms this test writes
function clean(list) {
const out = [];
for (const raw of list) {
let e = raw.trim();
if (e === "10.1.2.3/8") e = "10.0.0.0/8";
if (!/^[0-9a-f:.]+(\/\d+)?$/i.test(e)) return { error: `"${raw}" is not an IP address or range: write it as 203.0.113.7, 10.0.0.0/8 or 2001:db8::/32` };
if (!out.includes(e)) out.push(e);
}
if (out.length && out.every((e) => e.startsWith("172.16."))) return { error: "that allow list would shut out 203.0.113.50, the address this page is open from: add it first" };
return { ips: out };
}
function server(lang, posts, over) {
const s = settingsPayload({ lang, allowIPs: [], ...over });
return async (route) => {
const url = new URL(route.request().url());
const json = (data, status = 200) => route.fulfill({ json: data, status });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light"};` });
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" }, fx: s.fx });
if (url.pathname === "/api/settings") return json(s);
if (url.pathname === "/api/settings/allowips") {
const body = route.request().postDataJSON();
posts.push(body.ips);
if (s.allowIPsEnv) return json({ error: "MAGPIE_ALLOW_IPS sets the allow list; change it there" }, 400);
const c = clean(body.ips);
if (c.error) return json({ error: c.error }, 400);
s.allowIPs = c.ips;
return json(s);
}
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
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)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const en = {
name: "Allowed addresses", add: "Add", remove: "Remove", field: "IP address or range",
sub: "Other computers reach magpie only from these addresses or ranges (CIDR), even with a gateway key; this computer always can. None listed lets every address in",
envSub: "Set by MAGPIE_ALLOW_IPS. Other computers reach magpie only from these addresses, even with a gateway key; this computer always can",
notIP: "Write an address as 203.0.113.7, or a range as 10.0.0.0/8 or 2001:db8::/32",
shutOut: "That list leaves out the address this page is open from: add it first, or this page can’t reach magpie",
envSet: "MAGPIE_ALLOW_IPS sets this list; change it there",
};
const zh = { name: "允许的地址", add: "添加", remove: "移除" };
async function open(browser, lang, posts, over) {
const page = await (await browser.newContext({ viewport: { width: 390, height: 560 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, posts, over));
await watchSettingsReads(page);
await page.goto("http://127.0.0.1:4999/?view=settings&tab=network");
await settingsDrawn(page);
return { page, errors };
}
// every row fits the panel: nothing cut, nothing past the edge
async function fits(box) {
const bad = await box.evaluate((b) => {
const out = [];
const right = b.getBoundingClientRect().right + 0.5;
for (const e of b.querySelectorAll(".row, input, button, .name, .sub")) {
const r = e.getBoundingClientRect();
if (r.right > right || r.width === 0) out.push(e.className + " " + r.right + ">" + right);
if (e.matches("button, .name") && e.scrollWidth > e.clientWidth + 1) out.push("cut: " + e.textContent);
}
if (document.documentElement.scrollWidth > innerWidth) out.push("page scrolls sideways");
return out;
});
assert.deepEqual(bad, []);
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": allowed addresses are listed under Share on local network (lc)", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
await t.test("every language has the strings", async () => {
const { page } = await open(browser, "en", []);
for (const lang of ["zh", "zh-TW", "ja", "de"]) {
const missing = await page.evaluate(([lang, keys]) => keys.filter((k) => {
const d = I18N[lang];
return !d || !d[k] || d[k] === k;
}), [lang, Object.values(en).filter((s) => !["Add", "Remove"].includes(s))]);
assert.deepEqual(missing, [], lang);
}
await page.context().close();
});
await t.test("hidden while magpie answers only this computer", async () => {
const { page, errors } = await open(browser, "en", [], { lan: false, lanURLs: [] });
await page.locator("#lanList .row").first().waitFor();
assert.equal(await page.locator("#allowList .row").count(), 0);
assert.deepEqual(errors, []);
await page.context().close();
});
for (const lang of ["en", "zh"]) {
await t.test(lang, async () => {
const posts = [];
const { page, errors } = await open(browser, lang, posts);
const box = page.locator("#allowList");
await box.locator(".rule-row").waitFor();
const tr = (s) => page.evaluate((s) => t(s), s);
const w = {};
for (const [k, s] of Object.entries(en)) {
w[k] = await tr(s);
if (lang !== "en") assert.notEqual(w[k], s, `"${s}" has no ${lang} translation`);
if (lang === "zh" && zh[k]) assert.equal(w[k], zh[k]);
}
const row = box.locator(".rule-row");
assert.equal((await row.locator(".name").textContent()).trim(), w.name);
assert.equal((await row.locator(".sub").textContent()).trim(), w.sub);
const field = row.locator("input");
assert.equal(await field.getAttribute("aria-label"), w.field);
assert.equal(await page.locator("#allowList select").count(), 0);
await fits(box);
const view = page.locator("#view-settings");
const scroll = () => view.evaluate((v) => new Promise((ok) => requestAnimationFrame(() => requestAnimationFrame(() => ok(v.scrollTop)))));
await view.hover();
for (let i = 0; i < 40; i++) {
const r = await field.boundingBox();
if (r && r.y > 60 && r.y + r.height < 500 && (await scroll()) > 0) break;
await page.mouse.wheel(0, 120);
await page.waitForTimeout(30);
}
// added from the field, two at once: saved as the gateway cleaned them
await field.fill("203.0.113.50, 10.1.2.3/8");
let before = await scroll();
await row.locator("button", { hasText: w.add }).click();
await box.locator(".allow-ip-row .name", { hasText: "10.0.0.0/8" }).waitFor();
assert.deepEqual(posts.at(-1), ["203.0.113.50", "10.1.2.3/8"]);
assert.equal(await row.locator("input").inputValue(), "", "the field is left empty for the next one");
assert.equal(await scroll(), before, "Add moved the page");
// and with Enter
await row.locator("input").fill("2001:db8::/32");
await row.locator("input").press("Enter");
await box.locator(".allow-ip-row .name", { hasText: "2001:db8::/32" }).waitFor();
assert.deepEqual(posts.at(-1), ["203.0.113.50", "10.0.0.0/8", "2001:db8::/32"]);
await fits(box);
// refused, in the page's language, and nothing saved
await row.locator("input").fill("my-laptop");
before = await scroll();
await row.locator("button", { hasText: w.add }).click();
await page.waitForFunction((s) => document.querySelector("#allowList .rule-row .sub.err")?.textContent.trim() === s, w.notIP);
assert.equal(await row.locator("input").inputValue(), "my-laptop", "what the user wrote stays, to be corrected");
assert.equal(await box.locator(".allow-ip-row").count(), 3);
assert.equal(await scroll(), before, "a refusal moved the page");
await fits(box);
// taken away with its Remove
before = await scroll();
await box.locator(".allow-ip-row").filter({ hasText: "10.0.0.0/8" }).locator("button", { hasText: w.remove }).click();
await page.waitForFunction(() => document.querySelectorAll("#allowList .allow-ip-row").length === 2);
assert.deepEqual(posts.at(-1), ["203.0.113.50", "2001:db8::/32"]);
assert.equal(await scroll(), before, "Remove moved the page");
assert.equal((await row.locator(".sub").textContent()).trim(), w.sub, "a save clears the refusal");
const border = await box.locator(".row").first().evaluate((r) => getComputedStyle(r).borderLeftWidth);
assert(border === "0px" || border === "", "no left border accent: " + border);
assert.deepEqual(errors, []);
await page.context().close();
});
}
await t.test("a list that shuts out this page is refused", async () => {
const posts = [];
const { page, errors } = await open(browser, "zh", posts, { allowIPs: ["203.0.113.50"] });
const box = page.locator("#allowList");
const row = box.locator(".rule-row");
await row.waitFor();
await row.locator("input").fill("172.16.0.0/12");
await row.locator("button", { hasText: zh.add }).click();
// only this one: the old address taken away leaves the page out
await box.locator(".allow-ip-row", { hasText: "172.16.0.0/12" }).waitFor();
// scrolled with the wheel, as a reader would, until both rows show
await page.locator("#view-settings").hover();
for (let i = 0; i < 40; i++) {
const r = await box.locator(".allow-ip-row").last().boundingBox();
if (r && r.y > 60 && r.y + r.height < 460) break;
await page.mouse.wheel(0, 120);
await page.waitForTimeout(30);
}
await box.locator(".allow-ip-row").filter({ hasText: "203.0.113.50" }).locator("button").click();
const says = await page.evaluate((s) => t(s), en.shutOut);
await page.waitForFunction((s) => document.querySelector("#allowList .rule-row .sub.err")?.textContent.trim() === s, says);
assert.equal(await box.locator(".allow-ip-row").count(), 2, "nothing saved");
assert.deepEqual(errors, []);
await page.context().close();
});
await t.test("set by MAGPIE_ALLOW_IPS: shown, not edited", async () => {
const { page, errors } = await open(browser, "en", [], {
lan: false, lanURLs: [], onNetwork: true,
allowIPsEnv: "1.2.3.4,10.0.0.0/8", allowIPsFromEnv: ["1.2.3.4", "10.0.0.0/8"], allowIPs: ["9.9.9.9"],
});
const box = page.locator("#allowList");
await box.locator(".rule-row").waitFor();
assert.equal((await box.locator(".rule-row .sub").textContent()).trim(), en.envSub);
assert.deepEqual(await box.locator(".allow-ip-row .name").allTextContents(), ["1.2.3.4", "10.0.0.0/8"]);
assert.equal(await box.locator("input").count(), 0);
assert.equal(await box.locator("button").count(), 0);
await fits(box);
assert.deepEqual(errors, []);
await page.context().close();
});
});
}
+1 -1
View File
@@ -90,7 +90,7 @@ func StartWeb(addr, version string) (*Web, error) {
quit := func() { once.Do(func() { close(w.quit) }) }
w.Link = "http://" + net.JoinHostPort(host, port) + "/?k=" + url.QueryEscape(key)
w.srv = &http.Server{
Handler: webHandler(port, key, keep, Handler(webHost{quit}, startBackend())),
Handler: gateway.AllowGuard(webHandler(port, key, keep, Handler(webHost{quit}, startBackend()))),
ReadHeaderTimeout: 30 * time.Second,
}
go w.srv.Serve(ln)
+64
View File
@@ -0,0 +1,64 @@
package settings
import (
"fmt"
"net/netip"
"slices"
"strings"
)
// SplitAllowIPs splits MAGPIE_ALLOW_IPS ("1.2.3.4,10.0.0.0/8 2001:db8::/32")
// into its entries, at commas and spaces.
func SplitAllowIPs(v string) []string {
return strings.FieldsFunc(v, func(r rune) bool { return r == ',' || r == ';' || r == ' ' || r == '\t' || r == '\n' })
}
// ParseAllowIP reads one entry of the gateway's allow list: an IP address
// (IPv4 or IPv6, for itself alone) or a range in CIDR form. An IPv4
// address written as IPv6 (::ffff:1.2.3.4) is the IPv4 one.
func ParseAllowIP(raw string) (netip.Prefix, error) {
raw = strings.TrimSpace(raw)
bad := fmt.Errorf("%q is not an IP address or range: write it as 203.0.113.7, 10.0.0.0/8 or 2001:db8::/32", raw)
if raw == "" {
return netip.Prefix{}, bad
}
if strings.Contains(raw, "/") {
p, err := netip.ParsePrefix(raw)
if err != nil || p.Addr().Zone() != "" {
return netip.Prefix{}, bad
}
if p.Addr().Is4In6() && p.Bits() >= 96 {
p = netip.PrefixFrom(p.Addr().Unmap(), p.Bits()-96)
}
return p.Masked(), nil
}
a, err := netip.ParseAddr(strings.Trim(raw, "[]"))
if err != nil || a.Zone() != "" {
return netip.Prefix{}, bad
}
a = a.Unmap()
return netip.PrefixFrom(a, a.BitLen()), nil
}
// CleanAllowIPs checks each entry of an allow list and writes it in one
// form (an address alone, a range by its first address), without repeats.
func CleanAllowIPs(in []string) ([]string, error) {
var out []string
for _, raw := range in {
if strings.TrimSpace(raw) == "" {
continue
}
p, err := ParseAllowIP(raw)
if err != nil {
return nil, err
}
s := p.String()
if p.IsSingleIP() {
s = p.Addr().String()
}
if !slices.Contains(out, s) {
out = append(out, s)
}
}
return out, nil
}
+28
View File
@@ -0,0 +1,28 @@
package settings
import (
"slices"
"strings"
"testing"
)
// The allow list takes IPs and CIDR ranges, v4 and v6, writes each in one
// form, and refuses anything else with the forms it takes.
func TestCleanAllowIPs(t *testing.T) {
got, err := CleanAllowIPs([]string{" 203.0.113.7 ", "10.1.2.3/8", "2001:DB8::/32", "::ffff:198.51.100.1", "::ffff:198.51.100.0/120", "[2001:db8::5]", "203.0.113.7/32", ""})
if err != nil {
t.Fatal(err)
}
want := []string{"203.0.113.7", "10.0.0.0/8", "2001:db8::/32", "198.51.100.1", "198.51.100.0/24", "2001:db8::5"}
if !slices.Equal(got, want) {
t.Errorf("got %q, want %q", got, want)
}
for _, bad := range []string{"localhost", "10.0.0.0/33", "1.2.3", "fe80::1%en0", "fe80::/10%en0", "http://1.2.3.4"} {
if _, err := CleanAllowIPs([]string{bad}); err == nil || !strings.Contains(err.Error(), "is not an IP address") {
t.Errorf("%q: %v", bad, err)
}
}
if got := SplitAllowIPs("1.2.3.4,10.0.0.0/8 ; 2001:db8::/32\n"); !slices.Equal(got, []string{"1.2.3.4", "10.0.0.0/8", "2001:db8::/32"}) {
t.Errorf("split %q", got)
}
}
+6
View File
@@ -97,6 +97,12 @@ type Settings struct {
// reply, each with an enabled gateway key. None by default: a page
// gets no CORS headers, as before.
CORSOrigins []string `json:"corsOrigins,omitempty"`
// AllowIPs are the addresses (IPs and CIDR ranges) other computers may
// reach the gateway from at all (lc on Discord); any other is refused
// 403 even with a gateway key. None: every address, as before. This
// computer is always let in. MAGPIE_ALLOW_IPS, where set, is used in
// its place (gateway.AllowIPs).
AllowIPs []string `json:"allowIPs,omitempty"`
// Port is the gateway's port on this computer, 0 for DefaultPort.
// MAGPIE_ADDR, where it is set, comes first (GatewayAddr).
Port int `json:"port,omitempty"`
+2
View File
@@ -158,6 +158,7 @@ docker logs magpie</pre>
<tr><td><code>MAGPIE_ADDR</code></td><td>where the gateway listens. The image sets <code>0.0.0.0:3425</code>, so the published port reaches it.</td></tr>
<tr><td><code>MAGPIE_PUBLIC_URL</code></td><td>the address other machines reach the gateway at, such as <code>http://192.168.1.20:3425</code> (the host’s or the NAS’s, on the published port), or a reverse proxy’s base URL. In the container magpie sees only Docker’s own <code>172.17.x</code> address; with this set, the address it shows and prints is the one to use.</td></tr>
<tr><td><code>MAGPIE_WEB_KEY</code></td><td>the browser UI’s key, kept across restarts (16+ characters)</td></tr>
<tr><td><code>MAGPIE_ALLOW_IPS</code></td><td>the only addresses other machines may reach the gateway and the browser UI from, as IPs and CIDR ranges: <code>203.0.113.7,10.0.0.0/8,2001:db8::/32</code>. Any other address gets 403, even with a gateway key. Unset lets every address in, each with a key. See <a href="#allow">Allowed addresses</a>.</td></tr>
<tr><td><code>HOME</code>, <code>XDG_CONFIG_HOME</code>, <code>XDG_CACHE_HOME</code>, <code>XDG_DATA_HOME</code>, <code>XDG_STATE_HOME</code></td><td>set by the image to the folders under <code>/config</code> above; leave them</td></tr>
</table></div>
@@ -169,6 +170,7 @@ docker logs magpie</pre>
<p>On each other computer, point the agent at the gateway with one of those keys as its API key: <code>http://192.168.1.20:3425/v1</code> for an OpenAI client, <code>http://192.168.1.20:3425</code> for an Anthropic or Gemini one. Model ids are <code>provider/model</code>, or a routing group’s; <code>GET /v1/models</code> lists them. If that computer runs magpie itself, add the container as a <a href="/docs/remote">Remote magpie</a> instead, and magpie wires its agents for you.</p>
<p><span class="ui">Settings</span> → <span class="ui">Share on local network</span> isn’t needed in the container: turning it on also makes a gateway key named <span class="ui">Magpie</span>, and the gateway asks for a key from outside the container either way.</p>
<p><b>Upgrading from an earlier image.</b> An agent outside the container that sends <code>magpie</code>, 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.</p>
<p id="allow"><b>Allowed addresses.</b> On a public host, set <code>-e MAGPIE_ALLOW_IPS=203.0.113.7,10.0.0.0/8</code> 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 <code>X-Forwarded-For</code> 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 (<code>172.17.0.1</code>), 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 <span class="ui">Settings</span> → <span class="ui">Network and sharing</span> → <span class="ui">Allowed addresses</span>.</p>
<div class="callout"><b>Over the internet, prefer a VPN</b> such as Tailscale or WireGuard to opening 3425. A reverse proxy or tunnel in front of the container is the network too: its clients need a gateway key like any other machine’s.</div>
<h2 id="compose"><a class="anchor" href="#compose">Docker Compose on a NAS</a></h2>
+2
View File
@@ -158,6 +158,7 @@ docker logs magpie</pre>
<tr><td><code>MAGPIE_ADDR</code></td><td>ゲートウェイが待ち受けるアドレス。イメージでは <code>0.0.0.0:3425</code> に設定され、公開したポートから届きます。</td></tr>
<tr><td><code>MAGPIE_PUBLIC_URL</code></td><td>ほかのマシンがゲートウェイに届くアドレス。例:<code>http://192.168.1.20:3425</code>(ホストや NAS のアドレスと公開ポート)、またはリバースプロキシのベース URL。コンテナ内の magpie には Docker 自身の <code>172.17.x</code> のアドレスしか見えません。これを設定すると、表示されるアドレスが使うべきものになります。</td></tr>
<tr><td><code>MAGPIE_WEB_KEY</code></td><td>ブラウザ UI のキー。再起動しても変わりません(16 文字以上)</td></tr>
<tr><td><code>MAGPIE_ALLOW_IPS</code></td><td>ほかのマシンがゲートウェイとブラウザ UI に接続できるアドレス。IP または CIDR 範囲で書きます:<code>203.0.113.7,10.0.0.0/8,2001:db8::/32</code>。ほかのアドレスからは、ゲートウェイキーがあっても 403 になります。設定しなければすべてのアドレスから接続でき、それぞれキーが要ります。<a href="#allow">許可するアドレス</a>を参照。</td></tr>
<tr><td><code>HOME</code>、<code>XDG_CONFIG_HOME</code>、<code>XDG_CACHE_HOME</code>、<code>XDG_DATA_HOME</code>、<code>XDG_STATE_HOME</code></td><td>イメージが上の <code>/config</code> 配下のフォルダに設定しています。変えないでください</td></tr>
</table></div>
@@ -169,6 +170,7 @@ docker logs magpie</pre>
<p>ほかのコンピューターでは、エージェントをゲートウェイに向け、そのキーのどれかを API キーにします:OpenAI クライアントなら <code>http://192.168.1.20:3425/v1</code>、Anthropic や Gemini なら <code>http://192.168.1.20:3425</code>。モデル ID は <code>provider/model</code> かルーティンググループの名前で、<code>GET /v1/models</code> が一覧を返します。そのコンピューターでも magpie を動かしているなら、コンテナを<a href="/docs/ja/remote">リモート magpie</a> として追加すれば、magpie がエージェントを設定します。</p>
<p>コンテナでは <span class="ui">設定</span> → <span class="ui">ローカルネットワークで共有</span> は不要です。オンにすると <span class="ui">Magpie</span> という名前のゲートウェイキーも作られますが、ゲートウェイはどちらでもコンテナの外からのリクエストにキーを求めます。</p>
<p><b>以前のイメージからの更新。</b>コンテナの外から <code>magpie</code> や、有効なゲートウェイキーではないキーを送るエージェントは、401(“the API key sent is not an enabled magpie gateway key”)を受け取るようになります。上の手順でキーを作り、エージェントの設定に入れてください。すでにゲートウェイキーを送っているエージェントや、ゲートウェイキーで追加したリモート magpie はそのまま動きます。</p>
<p id="allow"><b>許可するアドレス。</b>公開ホストでは <code>-e MAGPIE_ALLOW_IPS=203.0.113.7,10.0.0.0/8</code> にクライアントのアドレスを書きます。ほかのアドレスからのリクエストはキーを見る前に 403 で拒否されるので、漏れたキーもよそからは使えません。拒否のメッセージとコンテナのログには、リクエスト元のアドレスが出ます。magpie が見るのは接続そのもののアドレスで、<code>X-Forwarded-For</code> ヘッダーは信用しません。書き間違えた項目は、すべてを通すのではなく、何も通しません。Docker 既定の bridge ネットワークはクライアント自身のアドレスをコンテナに渡しますが、ホスト自身からのリクエストは bridge のゲートウェイ(<code>172.17.0.1</code>)から届き、Docker Desktop や rootless Docker ではすべてのクライアントがそれ自身のひとつのアドレスに見えます。それを追加するか、403 に書かれたアドレスを確かめてください。リバースプロキシやトンネルの後ろでは、すべてのリクエストがプロキシのアドレスから届くので、接続できる人はプロキシで制限してください。デスクトップ版では同じリストが <span class="ui">設定</span> → <span class="ui">ネットワークと共有</span> → <span class="ui">許可するアドレス</span> にあります。</p>
<div class="callout"><b>インターネット越しなら VPN を</b>(Tailscale や WireGuard など)。3425 を開けるより安全です。コンテナの前に置くリバースプロキシやトンネルもネットワークです。そのクライアントにも、ほかのマシンと同じくゲートウェイキーが必要です。</div>
<h2 id="compose"><a class="anchor" href="#compose">NAS で Docker Compose</a></h2>
+2
View File
@@ -158,6 +158,7 @@ docker logs magpie</pre>
<tr><td><code>MAGPIE_ADDR</code></td><td>网关监听的地址。镜像里设为 <code>0.0.0.0:3425</code>,发布的端口才能访问到它。</td></tr>
<tr><td><code>MAGPIE_PUBLIC_URL</code></td><td>其他机器访问网关用的地址,例如 <code>http://192.168.1.20:3425</code>(宿主机或 NAS 的地址,加发布的端口),或反向代理的 base URL。容器里 magpie 只看得到 Docker 自己的 <code>172.17.x</code> 地址;设置后,它显示和打印的就是该用的地址。</td></tr>
<tr><td><code>MAGPIE_WEB_KEY</code></td><td>Web 界面的 key,重启后不变(16 个字符以上)</td></tr>
<tr><td><code>MAGPIE_ALLOW_IPS</code></td><td>其他机器只能从这些地址访问网关和 Web 界面,写 IP 或 CIDR 网段:<code>203.0.113.7,10.0.0.0/8,2001:db8::/32</code>。其他地址即使带着网关密钥也会得到 403。不设置则所有地址都可访问,各自仍需密钥。见<a href="#allow">允许的地址</a>。</td></tr>
<tr><td><code>HOME</code>、<code>XDG_CONFIG_HOME</code>、<code>XDG_CACHE_HOME</code>、<code>XDG_DATA_HOME</code>、<code>XDG_STATE_HOME</code></td><td>镜像已设为上面 <code>/config</code> 下的目录,不要改</td></tr>
</table></div>
@@ -169,6 +170,7 @@ docker logs magpie</pre>
<p>在其他电脑上,把 Agent 指向这个网关,用其中一个密钥作为 API key:OpenAI 客户端用 <code>http://192.168.1.20:3425/v1</code>,Anthropic 或 Gemini 客户端用 <code>http://192.168.1.20:3425</code>。模型 id 是 <code>provider/model</code> 或路由组的名字,<code>GET /v1/models</code> 会列出它们。如果那台电脑自己也运行 magpie,就把容器添加为<a href="/docs/zh/remote">远程 magpie</a>,由 magpie 替你配置 Agent。</p>
<p>容器里不需要打开 <span class="ui">设置</span> → <span class="ui">局域网共享</span>:打开它会另外生成一个名为 <span class="ui">Magpie</span> 的网关密钥,而不论开关如何,网关都会向容器外的请求要密钥。</p>
<p><b>从旧镜像升级。</b>容器外发送 <code>magpie</code> 或其他非启用网关密钥的 Agent,现在会收到 401(“the API key sent is not an enabled magpie gateway key”)。按上面的步骤给它生成一个密钥,填进 Agent 的设置。已经发送网关密钥的 Agent,以及用网关密钥添加的远程 magpie,照常工作。</p>
<p id="allow"><b>允许的地址。</b>在公网主机上,用 <code>-e MAGPIE_ALLOW_IPS=203.0.113.7,10.0.0.0/8</code> 写上你的客户端所在的地址。来自其他地址的请求在看密钥之前就被拒绝(403),所以泄露的密钥从别处也用不了;拒绝信息和容器日志都会写出请求来自的地址。magpie 判断的是连接本身的地址,从不采信 <code>X-Forwarded-For</code> 头;写错的条目不会放行任何地址,而不是放行所有地址。Docker 默认的 bridge 网络会把客户端自己的地址传进容器,但宿主机自己发出的请求来自 bridge 的网关(<code>172.17.0.1</code>),Docker Desktop 和 rootless Docker 则把所有客户端显示成它们自己的一个地址:把它加上,或看 403 里写的是哪个。在反向代理或隧道后面时,所有请求都来自代理的地址,请在代理那里限制谁能访问。桌面版里同一个列表在 <span class="ui">设置</span> → <span class="ui">网络与共享</span> → <span class="ui">允许的地址</span>。</p>
<div class="callout"><b>跨互联网访问时,优先用 VPN</b>(如 Tailscale 或 WireGuard),不要直接开放 3425。容器前面的反向代理或隧道也算网络:它的客户端和其他机器一样需要网关密钥。</div>
<h2 id="compose"><a class="anchor" href="#compose">在 NAS 上用 Docker Compose</a></h2>