Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gui: magpie web's port answers the gateway's /v1 routes too, so one proxy location serves both (zgcwkj on Discord)
yetone1b32bdcfcb76
diff --git a/docs/reference.md b/docs/reference.mdindex 69453a95a..dd151289c 100644--- a/docs/reference.md+++ b/docs/reference.md@@ -1780,8 +1780,18 @@ External clients behind a reverse proxy need an enabled gateway keythem, unless the proxy authenticates its clients itself(`MAGPIE_TRUST_PROXY=1`, below). A public URL with no port ofits own — a reverse proxy's `https://magpie.example.com` — is the address-`magpie web` prints for its own page too, so the proxy must forward `/v1`-and `/v1beta` to the gateway's port and the rest to the page's. When the+`magpie web` prints for its own page too. One location is enough: the+page's port (`127.0.0.1:3430`) answers the gateway's client routes as well+(`/v1/…`, `/v1beta/…`, `/mcp/…`, `/backend-api/codex/…` and the same+routes without `/v1`), handing them to the gateway, so a proxy that sends+everything to the page's port serves the page at `https://magpie.example.com/`+and the agents at `https://magpie.example.com/v1`. Those routes are judged+there exactly as on the gateway's port (the allow list, a gateway key from+another machine or through the proxy, the Origin and Host checks); the+page's sign-in cookie is no gateway key, and the page and its `/api` still+need the page's key. Ollama's `/api/*` and Claude Desktop's `/api/hello`+are the page's own namespace on that port, so a client of those is given+the gateway's own port. When theproxy and magpie run on the same machine, a request it forwards overloopback carries a forwarding header and needs a gateway key as one fromthe network does (see [Providers and the gateway](#providers-and-the-gateway)); a proxy that@@ -1823,8 +1833,9 @@ from `/api/tags`, each one's tools, vision, thinking and window from`/api/show`, and chats on `/v1/chat/completions`. Ollama's own chat(`/api/chat`, `/api/generate`, so `ollama run`) isn't served. Copilot sendsno key, so this works on this computer only; behind a reverse proxy with a-single public URL, `/api` goes to `magpie web`'s page, so give the-gateway's own port.+single public URL, `/api` goes to `magpie web`'s page (which answers the+gateway's `/v1` routes but not its `/api` ones), so give the gateway's own+port.Requests pass straight through when the vendor speaks the agent's API andare translated otherwise, streaming, tool calls and reasoning included. The@@ -2309,7 +2320,9 @@ The service serves only the gateway unless asked for the page:`magpie daemon install --web` (or `magpie daemon web on` once installed)runs `magpie serve --web`, which serves the gateway and `magpie web`'spage from one process, so the page shows the service's own gateway,-providers and accounts. It listens on `127.0.0.1:3430`; `--lan` puts it on+providers and accounts. It listens on `127.0.0.1:3430`, which answers the+gateway's `/v1` routes too (see [Connecting anything else](#connecting-anything-else)), so one+reverse-proxy location serves both; `--lan` puts it on`0.0.0.0:3430` and `--addr host:port` anywhere, with the same warning as`magpie web --lan`: anyone with the link can change your settings. Its keyis made once and kept in the service file (as `MAGPIE_WEB_KEY`, readable bydiff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex c32788c83..673752e0e 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -28,7 +28,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).| --- | --- | --- || 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. Claude Science, whose User-Agent is the Anthropic SDK's, is told by its client's `X-Anthropic-Surface: operon` (`isClaudeScience`). It is listed every model as `claude-magpie-<number>` (`scienceModels`; its picker keeps only a `claude-` id whose name isn't a lower-case slug), and a Claude id magpie doesn't serve (its default before a pick, its haiku side tasks) goes to the model its last turn with tools was on, else the first it is listed (`scienceTurn`, kept in `claude-science.model`). | [`gateway.go`](../../internal/gateway/gateway.go) || TLS | `--tls-cert`/`--tls-key` (`MAGPIE_TLS_CERT`, `MAGPIE_TLS_KEY`) make `ListenAndServe`, `Relisten` (both through `Server.listen`) and `magpie web`'s page (`ServeTLS`) wrap the listener in `tlsListener`. A connection from another computer is `tls.Server` at once, so its plain HTTP gets net/http's 400. One from this computer (`fromThisComputer`: loopback, or a peer address equal to the local one) is sniffed on its own goroutine, 10s at most (`sniffWait`), and 0x16 makes it TLS, so `URL()`, the agents, MCP servers, `ServedBy` and the healthcheck keep `http://127.0.0.1`. `certFiles.get` reloads the pair when either file's mtime or size changes; a pair that doesn't load keeps the one served (logged once per change). `tlsConfig` refuses half a pair or files that don't load before binding. HTTP/1.1 only over TLS (hijack, Codex's websocket). `Scheme()` gives the scheme of `LANURLs`, a scheme-less `MAGPIE_PUBLIC_URL` and the page's network links. Host and Origin checks (`foreignPage`, `rebound`) don't depend on the scheme. | [`tls.go`](../../internal/gateway/tls.go), [`lan.go`](../../internal/gateway/lan.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), Ollama's `GET /api/version`, `GET /api/tags` and `POST /api/show` (`ollama.go`, for a client that takes a custom endpoint only as an Ollama server: Visual Studio's and VS Code's Copilot, wani on Discord; the list is `catalogFor`'s, so a key's models alone, `/api/show` tells `capabilities` (`completion`, `tools`, `vision` from `Images`, `thinking` from `Thinks`) and `model_info` with `general.architecture` `magpie`, `general.basename`, `magpie.context_length` (32768, VS Code's own default, when the window isn't known, since VS Code would take a 0) and the `general.parameter_count` and `magpie.embedding_length` the ollama CLI before 0.7 reads unchecked; a name ending `:latest`, as the ollama CLI asks, is the bare id unless a model is really called that (`ollamaName`); the client then chats on `/v1/chat/completions`, or on Ollama's own `POST /api/chat` and `POST /api/generate` (`ollama_chat.go`, Zed's Ollama provider, super_lalalalala on Discord), which `ollamaChatBody` turns into a `/v1/chat/completions` body handed to the same `handle(provider.Chat)` on a clone of the request, so they are routed, held to a key's models and counted as it is: `messages` with `images` (base64, its type sniffed, as data-URL parts; a tool message's in a user message after it), an assistant's `thinking` as `reasoning_content` and its `tool_calls` given ids where Ollama sent none, a tool result matched to its call by `tool_call_id`, else `tool_name`, else in order (one with no call is a 400), `tools`, `format` (`json` or a schema), `think` (a level is `reasoning_effort`), and `options`' `temperature`, `top_p`, `seed`, `stop`, the two penalties and a positive `num_predict` as `max_tokens` (`num_ctx`, `top_k` and the rest of Ollama's own are dropped); `ollamaWriter` turns the reply into Ollama's NDJSON lines (streamed unless `stream:false`, then one object), tool calls with their `arguments` as an object and an `id`, and a last `done` line with `done_reason` and the token counts, and an error into `{"error":"…"}` with the status `/v1` would give; a request with no messages or prompt is answered `done_reason:"load"`, as Ollama does to warm a model), `/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. `/v1/magpie/heap` (`heapProfile`, [`heap.go`](../../internal/gateway/heap.go), for `magpie heap`) is held tighter than the rest by `heapRefused` in the handler itself, so it holds where `Handler` is served without `lanGuard` too: only a loopback caller that isn't proxied (`local`), carries no browser mark (`fromBrowser`) and names a loopback `Host` (`loopbackHost`) gets the profile; a gateway key never lets anything else in. `/v1/magpie/cpu` (`cpuProfile`, [`cpu.go`](../../internal/gateway/cpu.go), for `magpie cpu`) records a CPU profile for `?seconds=` (30, from 5 to 120) and is held to the same callers by `cpuRefused`, which shares `profileRefused` with `heapRefused`; one profile records at a time (`cpuRecording`), a second is answered 409, and a caller that hangs up stops it. `/v1/magpie/goroutines` (`goroutineDump`, [`goroutines.go`](../../internal/gateway/goroutines.go), for `magpie goroutines`, #3362) answers every goroutine's stack and wait as text (`runtime/pprof`'s `goroutine` profile at debug 2) to the same callers, through `goroutinesRefused`. `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). 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). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://<id>` (Chromium, the id 32 letters a–p), `moz-extension://<uuid>` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://<uuid>` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. 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`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. 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` but not a subdomain of it, which WebKit asks the DNS for (#2256), 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`, this computer's own, never brought by a sync or restore: see [sync and backup](sync-backup.md#what-stays-on-each-computer); 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. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `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`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`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), [`ollama.go`](../../internal/gateway/ollama.go), [`ollama_chat.go`](../../internal/gateway/ollama_chat.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), Ollama's `GET /api/version`, `GET /api/tags` and `POST /api/show` (`ollama.go`, for a client that takes a custom endpoint only as an Ollama server: Visual Studio's and VS Code's Copilot, wani on Discord; the list is `catalogFor`'s, so a key's models alone, `/api/show` tells `capabilities` (`completion`, `tools`, `vision` from `Images`, `thinking` from `Thinks`) and `model_info` with `general.architecture` `magpie`, `general.basename`, `magpie.context_length` (32768, VS Code's own default, when the window isn't known, since VS Code would take a 0) and the `general.parameter_count` and `magpie.embedding_length` the ollama CLI before 0.7 reads unchecked; a name ending `:latest`, as the ollama CLI asks, is the bare id unless a model is really called that (`ollamaName`); the client then chats on `/v1/chat/completions`, or on Ollama's own `POST /api/chat` and `POST /api/generate` (`ollama_chat.go`, Zed's Ollama provider, super_lalalalala on Discord), which `ollamaChatBody` turns into a `/v1/chat/completions` body handed to the same `handle(provider.Chat)` on a clone of the request, so they are routed, held to a key's models and counted as it is: `messages` with `images` (base64, its type sniffed, as data-URL parts; a tool message's in a user message after it), an assistant's `thinking` as `reasoning_content` and its `tool_calls` given ids where Ollama sent none, a tool result matched to its call by `tool_call_id`, else `tool_name`, else in order (one with no call is a 400), `tools`, `format` (`json` or a schema), `think` (a level is `reasoning_effort`), and `options`' `temperature`, `top_p`, `seed`, `stop`, the two penalties and a positive `num_predict` as `max_tokens` (`num_ctx`, `top_k` and the rest of Ollama's own are dropped); `ollamaWriter` turns the reply into Ollama's NDJSON lines (streamed unless `stream:false`, then one object), tool calls with their `arguments` as an object and an `id`, and a last `done` line with `done_reason` and the token counts, and an error into `{"error":"…"}` with the status `/v1` would give; a request with no messages or prompt is answered `done_reason:"load"`, as Ollama does to warm a model), `/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. `/v1/magpie/heap` (`heapProfile`, [`heap.go`](../../internal/gateway/heap.go), for `magpie heap`) is held tighter than the rest by `heapRefused` in the handler itself, so it holds where `Handler` is served without `lanGuard` too: only a loopback caller that isn't proxied (`local`), carries no browser mark (`fromBrowser`) and names a loopback `Host` (`loopbackHost`) gets the profile; a gateway key never lets anything else in. `/v1/magpie/cpu` (`cpuProfile`, [`cpu.go`](../../internal/gateway/cpu.go), for `magpie cpu`) records a CPU profile for `?seconds=` (30, from 5 to 120) and is held to the same callers by `cpuRefused`, which shares `profileRefused` with `heapRefused`; one profile records at a time (`cpuRecording`), a second is answered 409, and a caller that hangs up stops it. `/v1/magpie/goroutines` (`goroutineDump`, [`goroutines.go`](../../internal/gateway/goroutines.go), for `magpie goroutines`, #3362) answers every goroutine's stack and wait as text (`runtime/pprof`'s `goroutine` profile at debug 2) to the same callers, through `goroutinesRefused`. `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). 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). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://<id>` (Chromium, the id 32 letters a–p), `moz-extension://<uuid>` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://<uuid>` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. 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`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. 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` but not a subdomain of it, which WebKit asks the DNS for (#2256), 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`, this computer's own, never brought by a sync or restore: see [sync and backup](sync-backup.md#what-stays-on-each-computer); 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. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`), and its port hands the gateway's client routes (`ClientPath`) to `Server.Front`, the same lanGuard-over-Handler the gateway's listener serves, so every route there is judged as on the gateway's port (`TestClientPathCoversHandler` fails when a route Handler adds is in neither `ClientPath` nor its list of routes that stay on the gateway's port). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`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), [`ollama.go`](../../internal/gateway/ollama.go), [`ollama_chat.go`](../../internal/gateway/ollama_chat.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; the user's own groups only while the `groups` plugin is on, [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)), 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. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). 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) || A found group's two ids | A group magpie found is listed (`/v1/models`, the catalog, the lists written into agents, the pickers, the CLI and TUI) as `auto/<model>`: the model's id as a vendor spells it, dots kept and with no vendor prefix (`auto/claude-opus-5.5`; `provider.Group.Ref`, `spelledIn`, preferring a spelling models.dev lists), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). Its old id `group/auto-<slug>` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/<model>` (with `:level` or `[1m]`) back to it with `provider.CanonicalRef` before key limits, routing, affinity and the usage log see the request, and the request body is rewritten to it, so both ids count as one group. A gateway key naming either id, `group/*` or `auto/*` passes for both (`allows` in `key_models.go`). `SaveGroup` stores a member, rule or classifier picked as `auto/<model>` by the old id. An agent field magpie set to `group/auto-<slug>` moves to `auto/<model>` on the next `SyncCatalog` (`agent.renameFoundGroups`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/<model>`. An agent's hidden, picked and ordered models saved by the old id hold for the new one (`PublicRef` in `visible.go`), and a bare model id still reaches its found group (`bareTarget`). Claude Code is given a dotted Claude version dashed, so it may send `auto/claude-sonnet-4-5`: that is the same group, and `Reseat` still moves an agent off it once the group is gone (`samePick`). `auto` is no provider id: `Save` and `Rename` refuse it for a new provider, and a plugin's `auto` is `auto-plugin` (`PluginID`). A provider of the user's saved as `auto` before keeps its models: while it exists, `auto/<x>` is its model and found groups list as `group/auto-<slug>` (`autoRefsOn`). Hand-made groups stay `group/<id>`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.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) |diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.mdindex f77d39f97..2f3c4cb1a 100644--- a/docs/subsystems/gui-shell.md+++ b/docs/subsystems/gui-shell.md@@ -14,7 +14,7 @@ three.| Native host | `Run` starts the Wails v3 app: the tray icon, the panel, the main window, single-instance handover, `magpie://` import links and open at login. `host` implements `Windows` for the API: show and hide, open URLs and folders, copy to the clipboard, fit and tint the panel, and set the text size. A copy on Linux sets PRIMARY before CLIPBOARD, since GTK 3 serves CLIPBOARD empty when PRIMARY is set after it on a compositor with no primary selection (KDE Plasma with middle-click paste off, #1881); on Wayland the copy is read back through the compositor, and one that doesn't read back whole answers `/api/copy` with 501, so the page tries its clipboard API, then the copy command, then says the copy failed with the text to copy by hand (`copy-fallback.test.cjs`). | [`app.go`](../../internal/gui/app.go), [`clipboard_gtk3.go`](../../internal/gui/clipboard_gtk3.go), [`clipboard_gtk3.h`](../../internal/gui/clipboard_gtk3.h), [`mainwindow.go`](../../internal/gui/mainwindow.go), [`traymenu.go`](../../internal/gui/traymenu.go) || Backend | `startBackend` starts the gateway this process serves, unless another magpie already serves it. In that case this process only shows the other one's status (`gw` is nil). `stopServing` drains requests in flight. A restart to update can hand the listening socket to the new version instead (see [A restart to update hands the gateway over](#a-restart-to-update-hands-the-gateway-over)). | [`backend.go`](../../internal/gui/backend.go) || API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set`, `/api/agents/{action}/{id}` and `/api/agents/restart/{id}` (a desktop app's Restart, after the row's confirm). `held` lets one API request's reads share one catalog build (`provider.Hold`), and drops it after any write. `revalidated` and `versionedPage` name each script by its content hash, so a cache never serves an old `app.js` under a new page; a file asked for under its current hash (`?v=`) is cached for good (`immutable`), anything else is revalidated by its ETag. | [`api.go`](../../internal/gui/api.go) |-| Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304); the app's own windows read the page in-process and get it uncompressed. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go) |+| Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304); the app's own windows read the page in-process and get it uncompressed. The page's port answers the gateway's client routes too (`onePort`, `gateway.ClientPath`: `/v1/…`, `/v1beta/…`, `/mcp/…`, the Codex backend path and the routes without `/v1`; never `/api/*` or `/_magpie/*`, never a path that isn't clean), so one reverse-proxy location serves the page and the agents (zgcwkj on Discord). They skip the page's key and gzip and go to the gateway's own guards: `Server.Front` (lanGuard over Handler) in process when this process serves the gateway, or `toGateway`, a reverse proxy to `gateway.URL()`, when another magpie does; it keeps the Host and the forwarding headers and adds X-Forwarded-For for a peer that isn't loopback, so the other gateway judges the request as it came. See `TestWebOnePortServedHere`, `TestWebOnePortServedElsewhere` and `TestClientPathCoversHandler`. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go), [`oneport.go`](../../internal/gateway/oneport.go) || The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins/<id>/` (the Gateway, Sessions, Library, Routing and Usage pages, see [plugin runtime](plugin-runtime.md)) (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory (`openCtxText`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js`, and a plugin's own in its `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) || Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar), and the header a breadcrumb (`renderCrumb`). A page whose head holds only its tools (Library, Plugins, Settings) has them in the title bar after the breadcrumb, `tools` setting the room between it and the window's own buttons. When they don't fit there the tools show their icons alone (`tools-tight`; each keeps its name as `aria-label` and in its tooltip), then the breadcrumb drops its leading parts, and last the page's name is cut at its end, so no tool lies over the title (#2625, `title-bar-tools.test.cjs`). The open page's own tabs (`NAV_SUBS`: Usage, Library, Plugins, Settings) are listed under it as `.nav-s` rows (`role="tab"`, `data-of` the page tab's id) and the page's strip is hidden; a row's click clicks that tab at once, the selection (`.nav-hl`) having set off as the row was pressed (`navSubGlide`; back if the press leaves the row), and is the list's only shape: a row hovered or pressed has no ground of its own, and a `MutationObserver` draws the list again when the strip changes. A page's tabs share its one scroll, so a row that picks another tab opens it at its top (`scrollOnPurpose` with the row's click); the tab already open, picked again, leaves the page where it is (`sidebar-tab-top.test.cjs`). The list opens and folds with an iOS-like spring (`navSubEnter`, `navSubLeave`; none under reduced motion), and a folding list is out of reach at once. The open page's own row is marked the same way, by one shape (`.nav-top-hl`, the rows' own ground given up to it, hovered or pressed too) that `navTopGo` moves to the row picked on a damped spring, as iOS moves a selection (`NAV_SPRING`, SwiftUI's response 0.42s and damping 0.84; `navTopStep` steps it each frame): it sets off as the row is pressed and comes back if the press leaves the row or the page isn't left, turns with the speed it has when the press changes its mind, and follows its row while the list above it folds, landing where the row ends up. It is put in place, not sent, when the window opens on a page or the rows move under it at rest (a `ResizeObserver`), is away while Settings is open (it has its own selection at the foot), comes back fading in on its row, jumps under reduced motion, and isn't drawn in the header's tabs, which have their `.thumb`. `#nav` is `position: relative` in the sidebar for it, so `.seg`'s centring `left` and `top` are reset. See `sidebar-glide.test.cjs`. Narrower, the page beside a sidebar would be narrower than Usage's requests table needs (768 points), so they go back into the header's row, as a Mac sidebar gives way in a narrow window. At every width the reader can pick the sidebar or the header's tabs from the title bar's button (`#sideToggle`, ⌃⌘S or Ctrl+Shift+S; `toggleSideNav`), kept in localStorage `magpie.navLayout` (`side` or `top`) and so laid out from the first frame; none picked, the sidebar comes from `SIDE_AT`. Picked in a narrow window the sidebar is narrower (184 points under 860), and magpie web on a phone keeps its own tab bar and has no button. The two layouts trade places in a view transition (`navMorph`, app.css `.nav-morph`): the sidebar slides, each page's tab flies to its place in the other, and the page slides as one (its old image dropped, so no line prints twice); without view transitions, under reduced motion, or in the Linux app the change is at once: WebKitGTK with compositing off (`WEBKIT_DISABLE_COMPOSITING_MODE`, which `webkit_linux.go` sets under Wayland) crashes in a view transition. Elsewhere a transition still going after `MORPH_MAX` (1.5s) is skipped, so a webview that never ends one can't leave the window on the old layout's picture. See `side-toggle.test.cjs`. A window made wider or narrower drops what a click held (`heldWidth`): the page laid out again isn't the click's doing. The reader's own place is kept instead for a second while the page is laid out again (`relaid`, a `ResizeObserver` on the open page's parts calling `backToReader`): crossing `SIDE_AT` the browser clamps the scroll to each layout it passes through, and the page ended short of its foot (#1672, `text-size.test.cjs`). See `sidebar.test.cjs`. A sidebar longer than a short window keeps no scroll bar beside its pages: the native bars of `.side-scroll` and `.side-foot` are hidden, and `sideBars` lays a thin bar over each box's edge that shows while it scrolls, fades about a second after it stops (kept while hovered or dragged), can be dragged or clicked to page, and is gone when the box fits, the same in WebKit, WebView2 and WebKitGTK. See `sidebar-overlay-scrollbar.test.cjs`. The window opens on the page the reader last left, as a Mac app comes back as it was (molvqingtai and lc on Discord): `show` keeps the page in localStorage `magpie.lastView` (which the app's webview keeps across restarts, as it keeps `magpie.navLayout`), and `keptView` opens it at start. A page asked for in the address (`?view=`, the tray's links, a reload) wins, Agents too; a kept name that is no page opens the first page, and one gateway mode leaves out opens Providers (`show`). Opening on it scrolls nothing. See `last-page.test.cjs`. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/app.css`](../../internal/gui/assets/app.css) || Settings › Privacy | The page opens on what masking kept from vendors (`drawMaskObs` in app.js, fed by `/api/masking/summary`): the values masked over 7 or 30 days with a chart of the days, the kinds, what only the local model found, agents to providers, and the values masked most, each shown only while pointed at (`maskTip`, `/api/masking/value`, which says it is gone after a restart). Its records (`drawMaskRecs`, `/api/masking/records` and `/api/masking/record`) take the page's place, filtered by kind, finder, agent or provider, a day at a time, each opening on the text the vendor saw with its placeholders marked. `maskedBadge`, on the Gateway page's recent calls and the Routing page's log, opens a request's own record (`openMaskRecord`), in amber with the count sent as written when every value found was on Warn. Below the card, *What to mask*, *How it's found* (the rules, always on while anything is masked, and the local model on top of them), *When a value is found* (Mask, Warn or Block per kind, the secret kinds first and the personal ones behind *Show all kinds*, and the *Never mask* list; `renderMaskActions`), *Try it* (`renderMaskTry`, the text as the vendor would get it from `/api/masking/preview`, kept in no storage) and *Sharing*. See [gateway routing](gateway-routing.md) for what is recorded. | [`assets/app.js`](../../internal/gui/assets/app.js), [`masking.go`](../../internal/gui/masking.go) |diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex b920924c4..4a12e7dba 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -403,6 +403,9 @@ type Server struct {// taken off it (see Relisten)lnMu sync.Mutexln net.Listener+ // front is Front's handler, built once+ frontOnce sync.Once+ front http.Handler// handedOff: another magpie serves the port now, and this one's end// waits for its requests in flight to finish (handover.go)handedOff atomic.Bool@@ -582,7 +585,7 @@ func (s *Server) ListenAndServe(ctx context.Context) error {freshCtx, stopFresh := context.WithCancel(ctx)defer stopFresh()go pluginrt.KeepFresh(freshCtx, 2*time.Second, settings.Path(), provider.Path(), plugin.ListPath(), plugin.ToolsPath(), access.Path())- srv := &http.Server{Handler: lanGuard(s.Handler()), ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 5 * time.Minute}+ srv := &http.Server{Handler: s.Front(), ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 5 * time.Minute}// the magpie serving the gateway, and only it, keeps the saved accounts// signed in, so two never refresh one sign-in at oncego provider.KeepLoginsAlive(ctx)diff --git a/internal/gateway/oneport.go b/internal/gateway/oneport.gonew file mode 100644index 000000000..d901c4ca9--- /dev/null+++ b/internal/gateway/oneport.go@@ -0,0 +1,46 @@+package gateway++import (+ "net/http"+ "path"+ "strings"+)++// Front is what the gateway's own listener serves: Handler behind+// lanGuard, built once. `magpie web`'s port hands the gateway's client+// routes (ClientPath) to it too, so a request there is judged exactly as+// one on the gateway's port: the allow list, a key from another machine+// or through a proxy, a rebound page's Host, and corsGuard's Origin rules.+func (s *Server) Front() http.Handler {+ s.frontOnce.Do(func() { s.front = lanGuard(s.Handler()) })+ return s.front+}++// clientPrefixes are the gateway's client routes (Handler) that a page+// served on a port of its own passes on to the gateway: everything an+// agent or an SDK calls with the gateway as its base URL.+var clientPrefixes = []string{+ "/v1", "/v1beta",+ "/models", "/chat/completions", "/responses", "/messages",+ "/images", "/embeddings", "/rerank", "/audio", "/videos",+ "/muse-code/models", CodexPath, AlphaSearchPath, "/mcp",+}++// ClientPath: p is one of the gateway's client routes, which `magpie web`+// answers on its own port too by handing it to the gateway, so one address+// (one reverse-proxy location) serves the page and the agents (zgcwkj on+// Discord). The page's own routes keep its key: /api/* is the page's, so+// the Ollama and Claude Desktop routes there, and the Claude helper's+// callbacks under /_magpie/, stay on the gateway's port alone. A path that+// isn't clean (a "..", a "//") is none, and stays behind the page's key.+func ClientPath(p string) bool {+ if p == "" || path.Clean(p) != strings.TrimSuffix(p, "/") && p != "/" {+ return false+ }+ for _, pre := range clientPrefixes {+ if p == pre || strings.HasPrefix(p, pre+"/") {+ return true+ }+ }+ return false+}diff --git a/internal/gateway/oneport_test.go b/internal/gateway/oneport_test.gonew file mode 100644index 000000000..85c0b6a22--- /dev/null+++ b/internal/gateway/oneport_test.go@@ -0,0 +1,75 @@+package gateway++import (+ "os"+ "regexp"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/provider"+)++// Every route Handler registers is either a client route `magpie web`'s+// port hands to the gateway (ClientPath), or one named here that stays on+// the gateway's port alone: its info page at /, the /api/* routes (the+// page's own namespace there) and the Claude helper's callbacks under+// /_magpie/. A route added to Handler and to neither fails this, so the+// one-port page doesn't miss it, or take it, by accident.+func TestClientPathCoversHandler(t *testing.T) {+ src, err := os.ReadFile("gateway.go")+ if err != nil {+ t.Fatal(err)+ }+ start := strings.Index(string(src), "func (s *Server) Handler() http.Handler {")+ end := strings.Index(string(src)[start:], "\n}\n")+ body := string(src)[start : start+end]+ consts := map[string]string{+ "claudeMCPPath": claudeMCPPath, "CodexPath": CodexPath, "CodexCatalogPath": CodexCatalogPath,+ "AlphaSearchPath": AlphaSearchPath, "HeapPath": HeapPath, "CPUPath": CPUPath,+ "GoroutinesPath": GoroutinesPath, "SearchMCPPath": SearchMCPPath, "VisionMCPPath": VisionMCPPath,+ "ToolsMCPPath": ToolsMCPPath, "provider.RemoteCardsPath": provider.RemoteCardsPath,+ "provider.RemoteRefreshPath": provider.RemoteRefreshPath,+ }+ re := regexp.MustCompile(`mux\.HandleFunc\(((?:"[^"]*"|[A-Za-z.]+)(?:\s*\+\s*(?:"[^"]*"|[A-Za-z.]+))*),`)+ n := 0+ for _, m := range re.FindAllStringSubmatch(body, -1) {+ pat := ""+ for _, part := range strings.Split(m[1], "+") {+ part = strings.TrimSpace(part)+ if strings.HasPrefix(part, `"`) {+ pat += strings.Trim(part, `"`)+ } else if v, ok := consts[part]; ok {+ pat += v+ } else {+ t.Fatalf("Handler names %s, which this test doesn't know: add it to consts", part)+ }+ }+ if i := strings.IndexByte(pat, ' '); i >= 0 {+ pat = pat[i+1:]+ }+ p := strings.NewReplacer("{$}", "", "{id...}", "x", "{call...}", "x", "{id}", "x", "{token}", "x", "{name}", "x").Replace(pat)+ n+++ stays := p == "/" || strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/_magpie/")+ if ClientPath(p) == stays {+ t.Errorf("%s (%s): ClientPath %v", pat, p, ClientPath(p))+ }+ }+ if n < 60 {+ t.Fatalf("found %d routes in Handler: the pattern no longer reads it", n)+ }+}++// A path that isn't clean stays behind the page's key: the gateway's mux+// would redirect it elsewhere, and "/v1/../api/state" is the page's API.+func TestClientPathOnlyClean(t *testing.T) {+ for _, p := range []string{"", "/", "/api/state", "/api/v1/models", "/v1/../api/state", "/v1//models", "/v1/./models", "/v1x", "/v1betax/models", "/boot.js", "/_magpie/sign-in", "/mcpx", "/v1/models/../../api/settings"} {+ if ClientPath(p) {+ t.Errorf("%q is a client path", p)+ }+ }+ for _, p := range []string{"/v1", "/v1/", "/v1/models", "/v1/chat/completions", "/v1beta/models/gemini:generateContent", "/mcp/magpie/tools", "/backend-api/codex/responses", "/messages"} {+ if !ClientPath(p) {+ t.Errorf("%q is not a client path", p)+ }+ }+}diff --git a/internal/gui/web.go b/internal/gui/web.goindex 36728a895..8283cda3e 100644--- a/internal/gui/web.go+++ b/internal/gui/web.go@@ -10,6 +10,7 @@ import ("log""net""net/http"+ "net/http/httputil""net/url""os""strings"@@ -103,7 +104,7 @@ func StartWeb(addr, version string) (*Web, error) {}w.Link = scheme + "://" + net.JoinHostPort(host, port) + "/?k=" + url.QueryEscape(key)w.srv = &http.Server{- Handler: gateway.AllowGuard(webHandler(port, key, keep, Handler(webHost{quit}, startBackend()))),+ Handler: webServed(port, key, keep, Handler(webHost{quit}, startBackend())),ReadHeaderTimeout: 30 * time.Second,}go w.srv.Serve(ln)@@ -321,6 +322,13 @@ func LANAddrs() []string {return out}+// webServed is all `magpie web` on port serves: the gateway's client+// routes, judged by the gateway (onePort), and the page and its API behind+// the allow list and the key.+func webServed(port, key string, keep time.Duration, page http.Handler) http.Handler {+ return onePort(gateway.AllowGuard(webHandler(port, key, keep, page)))+}+// webHandler is what `magpie web` on port serves: the page and its API// behind the key, compressed for the browser.func webHandler(port, key string, keep time.Duration, page http.Handler) http.Handler {@@ -375,3 +383,61 @@ func compressible(ct string) bool {// isWeb: the page is served to a browser by `magpie web`.func isWeb(w Windows) bool { _, ok := w.(webHost); return ok }++// onePort hands the gateway's client routes (gateway.ClientPath: /v1/…,+// /v1beta/…, /mcp/…) on the page's port to the gateway, so the page and the+// agents share one address and a reverse proxy needs one location for both+// (zgcwkj on Discord). Each such request is judged by the gateway's own+// guards (Server.Front), not the page's key: an agent has no cookie, and a+// request from another machine or through a proxy needs a gateway key+// while magpie is shared, as on the gateway's port. Everything else (the+// page, its /api/*) stays behind the page's allow list and key.+func onePort(page http.Handler) http.Handler {+ return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {+ if !gateway.ClientPath(r.URL.Path) {+ page.ServeHTTP(rw, r)+ return+ }+ if gw := served.Load(); gw != nil {+ gw.Front().ServeHTTP(rw, r)+ return+ }+ toGateway.ServeHTTP(rw, r)+ })+}++// toGateway passes a client route on to the gateway another magpie serves+// here (the service, the app), as it came: its Host, so a rebound page's+// name is still refused, and its forwarding headers, so a request a proxy+// passed on is still one from another machine. One from another machine+// straight to this port gets the peer's address added as X-Forwarded-For,+// as the gateway would otherwise see this process's loopback call and ask+// it no key.+var toGateway = &httputil.ReverseProxy{+ Rewrite: func(pr *httputil.ProxyRequest) {+ u, _ := url.Parse(gateway.URL())+ pr.SetURL(u)+ pr.Out.Host = pr.In.Host+ // Rewrite starts from a request with these taken off+ for _, h := range []string{"Forwarded", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto"} {+ if v := pr.In.Header.Values(h); len(v) > 0 {+ pr.Out.Header[h] = append([]string(nil), v...)+ }+ }+ if !loopbackPeer(pr.In.RemoteAddr) {+ pr.SetXForwarded()+ }+ },+ FlushInterval: -1, // streams as they come+ ErrorHandler: func(rw http.ResponseWriter, r *http.Request, err error) {+ log.Printf("magpie web: %s %s: the gateway at %s: %v", r.Method, r.URL.Path, gateway.URL(), err)+ http.Error(rw, "magpie's gateway at "+gateway.URL()+" doesn't answer: "+err.Error(), http.StatusBadGateway)+ },+}++// loopbackPeer: addr (a RemoteAddr) is on this computer's loopback.+func loopbackPeer(addr string) bool {+ h, _, err := net.SplitHostPort(addr)+ ip := net.ParseIP(h)+ return err == nil && ip != nil && ip.IsLoopback()+}diff --git a/internal/gui/web_oneport_test.go b/internal/gui/web_oneport_test.gonew file mode 100644index 000000000..d89f8887a--- /dev/null+++ b/internal/gui/web_oneport_test.go@@ -0,0 +1,188 @@+package gui++import (+ "io/fs"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/access"+ "github.com/yetone/magpie/internal/gateway"+ "github.com/yetone/magpie/internal/settings"+)++// onePortHome is a fresh magpie home for one test: settings and keys of+// its own.+func onePortHome(t *testing.T) {+ t.Helper()+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_CACHE_HOME", t.TempDir())+ t.Setenv("MAGPIE_ADDR", "")+ t.Setenv("MAGPIE_PUBLIC_URL", "")+ t.Setenv("MAGPIE_TRUST_PROXY", "")+}++// onePortKey shares magpie and makes an enabled gateway key.+func onePortKey(t *testing.T) string {+ t.Helper()+ s := settings.Load()+ s.LAN = true+ if err := settings.Save(s); err != nil {+ t.Fatal(err)+ }+ k, err := access.Update("add-key", access.Change{Name: "nginx"})+ if err != nil {+ t.Fatal(err)+ }+ return k+}++// onePortCall is a request to h from peer, with hdr's pairs, the page's+// cookie added when cookie isn't "".+func onePortCall(t *testing.T, h http.Handler, method, target, peer, host, cookie string, hdr ...string) *httptest.ResponseRecorder {+ t.Helper()+ var body *strings.Reader+ if method == "POST" {+ body = strings.NewReader(`{"model":"none/none","messages":[{"role":"user","content":"hi"}]}`)+ } else {+ body = strings.NewReader("")+ }+ r := httptest.NewRequest(method, target, body)+ r.RemoteAddr = peer+ r.Host = host+ r.Header.Set("Content-Type", "text/plain") // a page's "simple" POST+ for i := 0; i+1 < len(hdr); i += 2 {+ r.Header.Set(hdr[i], hdr[i+1])+ }+ if cookie != "" {+ r.AddCookie(&http.Cookie{Name: "magpie_web_3430", Value: cookie})+ }+ w := httptest.NewRecorder()+ h.ServeHTTP(w, r)+ return w+}++var chromeMarks = []string{"User-Agent", "Mozilla/5.0 (Macintosh) Chrome/140", "Sec-Fetch-Site", "same-origin", "Sec-Fetch-Mode", "cors"}++// onePortCases checks what `magpie web`'s port answers, the gateway being+// reached through gw (this process's, or another magpie's): its client+// routes as the gateway's own port would, and the page's API never without+// the page's key, whatever route, Origin or Host a request takes.+func onePortCases(t *testing.T, h http.Handler, reached *bool) {+ t.Helper()+ const lo, here = "127.0.0.1:50001", "127.0.0.1:3430"+ const evil = "rebind.attacker.example:3430"+ api := func(name, method, target, peer, host string, hdr ...string) {+ t.Helper()+ *reached = false+ w := onePortCall(t, h, method, target, peer, host, "", hdr...)+ if *reached || w.Code < 300 || w.Code == http.StatusMovedPermanently {+ t.Errorf("the page's API %s: %d, reached %v: %s", name, w.Code, *reached, w.Body.String())+ }+ }+ // the page's API: no cookie, no way in+ api("with no Origin", "GET", "/api/settings", lo, here)+ api("with no Origin, a POST", "POST", "/api/settings", lo, here)+ api("from Origin: null", "POST", "/api/settings", lo, here, "Origin", "null")+ api("from a foreign Origin", "POST", "/api/settings", lo, here, "Origin", "https://evil.example")+ api("under a rebound Host", "GET", "/api/settings", lo, evil, chromeMarks...)+ api("under a rebound Host, a POST", "POST", "/api/settings", lo, evil, append([]string{"Origin", "http://" + evil}, chromeMarks...)...)+ api("through a proxy", "GET", "/api/settings", lo, "magpie.example.com", "X-Forwarded-For", "203.0.113.9")+ api("from another machine", "GET", "/api/settings", "10.0.0.5:50001", here)+ // nor by a path that names a client route on its way to the API+ api("by /v1/../api", "GET", "/v1/../api/settings", lo, here)+ api("by /v1/%2e%2e/api", "GET", "/v1/%2e%2e/api/settings", lo, here)+ api("by /v1//api", "GET", "/v1//api/settings", lo, here)+ // a gateway key is no key to the page+ key := onePortKey(t)+ api("with a gateway key", "GET", "/api/settings", lo, here, "Authorization", "Bearer "+key)++ *reached = false+ if w := onePortCall(t, h, "POST", "/api/settings", lo, here, onePortWebKey); w.Code != http.StatusTeapot || !*reached {+ t.Fatalf("the page's API with its cookie: %d", w.Code)+ }++ gw := func(name string, want int, method, target, peer, host, cookie string, hdr ...string) {+ t.Helper()+ *reached = false+ w := onePortCall(t, h, method, target, peer, host, cookie, hdr...)+ if w.Code != want || *reached {+ t.Errorf("the gateway %s: %d, want %d (page reached %v): %s", name, w.Code, want, *reached, w.Body.String())+ }+ }+ // the gateway's client routes, judged as on its own port+ gw("for an agent here", 200, "GET", "/v1/models", lo, here, "")+ gw("from Origin: null", 403, "POST", "/v1/chat/completions", lo, here, "", "Origin", "null")+ gw("from a foreign Origin", 403, "POST", "/v1/chat/completions", lo, here, "", "Origin", "https://evil.example")+ gw("under a rebound Host", 403, "GET", "/v1/models", lo, evil, "", chromeMarks...)+ gw("under a rebound Host, a POST", 403, "POST", "/v1/chat/completions", lo, evil, "", append([]string{"Origin", "http://" + evil}, chromeMarks...)...)+ // the page's own cookie is no gateway key either+ gw("under a rebound Host with the page's cookie", 403, "GET", "/v1/models", lo, evil, onePortWebKey, chromeMarks...)+ gw("through a proxy without a key", 401, "GET", "/v1/models", lo, "magpie.example.com", "", "X-Forwarded-For", "203.0.113.9")+ gw("through a proxy with the page's cookie", 401, "GET", "/v1/models", lo, "magpie.example.com", onePortWebKey, "X-Forwarded-For", "203.0.113.9")+ gw("from another machine without a key", 401, "GET", "/v1/models", "10.0.0.5:50001", here, "")+ gw("through a proxy with a gateway key", 200, "GET", "/v1/models", lo, "magpie.example.com", "", "X-Forwarded-For", "203.0.113.9", "Authorization", "Bearer "+key)+ gw("from another machine with a gateway key", 200, "GET", "/v1/models", "10.0.0.5:50001", here, "", "Authorization", "Bearer "+key)++ // not shared: another machine, or a proxy, isn't answered at all+ s := settings.Load()+ s.LAN = false+ if err := settings.Save(s); err != nil {+ t.Fatal(err)+ }+ gw("through a proxy, not shared", 403, "GET", "/v1/models", lo, "magpie.example.com", "", "X-Forwarded-For", "203.0.113.9", "Authorization", "Bearer "+key)+ gw("from another machine, not shared", 403, "GET", "/v1/models", "10.0.0.5:50001", here, "", "Authorization", "Bearer "+key)+}++const onePortWebKey = "0123456789abcdef0123456789abcdef"++func onePortPage(reached *bool) http.Handler {+ return webServed("3430", onePortWebKey, 0, http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {+ *reached = true+ rw.WriteHeader(http.StatusTeapot)+ }))+}++// zgcwkj on Discord: one reverse-proxy location for the page and the+// agents. `magpie web`'s port hands the gateway's client routes to the+// gateway this process serves, through the gateway's own guards.+func TestWebOnePortServedHere(t *testing.T) {+ onePortHome(t)+ g := gateway.New()+ prev := served.Swap(g)+ t.Cleanup(func() { served.Store(prev) })+ var reached bool+ onePortCases(t, onePortPage(&reached), &reached)+}++// With another magpie serving the gateway (the service, the app), the page+// passes the client routes on to it, and they are judged there as they+// came: Host, Origin and a proxy's forwarding headers kept, and one from+// another machine marked as such.+func TestWebOnePortServedElsewhere(t *testing.T) {+ onePortHome(t)+ other := httptest.NewServer(gateway.New().Front())+ t.Cleanup(other.Close)+ u, _ := url.Parse(other.URL)+ t.Setenv("MAGPIE_ADDR", u.Host)+ prev := served.Swap(nil)+ t.Cleanup(func() { served.Store(prev) })+ var reached bool+ onePortCases(t, onePortPage(&reached), &reached)+}++// No file of the page is at a client route, where the gateway would+// answer in its place.+func TestWebAssetsAreNoClientPath(t *testing.T) {+ fs.WalkDir(staticFS(), ".", func(p string, d fs.DirEntry, err error) error {+ if err == nil && gateway.ClientPath("/"+p) {+ t.Errorf("the page's /%s is a gateway client route", p)+ }+ return nil+ })+}diff --git a/site/public/docs/docker.html b/site/public/docs/docker.htmlindex 4fb76c85c..4410ef694 100644--- a/site/public/docs/docker.html+++ b/site/public/docs/docker.html@@ -89,7 +89,7 @@<div class="table-wrap"><table><tr><td><b>Image</b></td><td><code>ghcr.io/yetone/magpie</code>, for <code>linux/amd64</code> and <code>linux/arm64</code></td></tr><tr><td><b>Tags</b></td><td><code>latest</code> (the newest release), <code>0.1.1150</code> (one release), <code>0.1</code>, <code>edge</code> (every change on <code>main</code>)</td></tr>- <tr><td><b>Ports</b></td><td><code>3425</code> the gateway agents call; <code>3430</code> the browser UI, when the container runs <code>magpie web</code></td></tr>+ <tr><td><b>Ports</b></td><td><code>3425</code> the gateway agents call; <code>3430</code> the browser UI, when the container runs <code>magpie web</code>; it answers the gateway’s <code>/v1</code> routes too, so a reverse proxy needs only this port</td></tr><tr><td><b>Volume</b></td><td><code>/config</code>: providers, keys, sign-ins, plugins and usage</td></tr><tr><td><b>User</b></td><td>nonroot (uid 65532)</td></tr></table></div>diff --git a/site/public/docs/ja/docker.html b/site/public/docs/ja/docker.htmlindex 5ac69181c..20457ef44 100644--- a/site/public/docs/ja/docker.html+++ b/site/public/docs/ja/docker.html@@ -89,7 +89,7 @@<div class="table-wrap"><table><tr><td><b>イメージ</b></td><td><code>ghcr.io/yetone/magpie</code>(<code>linux/amd64</code> と <code>linux/arm64</code>)</td></tr><tr><td><b>タグ</b></td><td><code>latest</code>(最新リリース)、<code>0.1.1150</code>(特定のリリース)、<code>0.1</code>、<code>edge</code>(<code>main</code> の変更ごと)</td></tr>- <tr><td><b>ポート</b></td><td><code>3425</code> はエージェントが呼ぶゲートウェイ、<code>3430</code> はコンテナが <code>magpie web</code> を動かすときのブラウザ UI</td></tr>+ <tr><td><b>ポート</b></td><td><code>3425</code> はエージェントが呼ぶゲートウェイ、<code>3430</code> はコンテナが <code>magpie web</code> を動かすときのブラウザ UI。ゲートウェイの <code>/v1</code> ルートにも応えるので、リバースプロキシはこのポートだけで足ります</td></tr><tr><td><b>ボリューム</b></td><td><code>/config</code>:プロバイダ、キー、サインイン、プラグイン、使用量</td></tr><tr><td><b>ユーザー</b></td><td>nonroot(uid 65532)</td></tr></table></div>diff --git a/site/public/docs/zh/docker.html b/site/public/docs/zh/docker.htmlindex 7d5e6bcab..1adbd5d00 100644--- a/site/public/docs/zh/docker.html+++ b/site/public/docs/zh/docker.html@@ -89,7 +89,7 @@<div class="table-wrap"><table><tr><td><b>镜像</b></td><td><code>ghcr.io/yetone/magpie</code>,支持 <code>linux/amd64</code> 和 <code>linux/arm64</code></td></tr><tr><td><b>标签</b></td><td><code>latest</code>(最新正式版)、<code>0.1.1150</code>(某个版本)、<code>0.1</code>、<code>edge</code>(<code>main</code> 上的每次改动)</td></tr>- <tr><td><b>端口</b></td><td><code>3425</code> 是 Agent 调用的网关;<code>3430</code> 是容器运行 <code>magpie web</code> 时的 Web 界面</td></tr>+ <tr><td><b>端口</b></td><td><code>3425</code> 是 Agent 调用的网关;<code>3430</code> 是容器运行 <code>magpie web</code> 时的 Web 界面;它也响应网关的 <code>/v1</code> 路由,所以反向代理只需转发这一个端口</td></tr><tr><td><b>数据卷</b></td><td><code>/config</code>:供应商、密钥、登录、插件和用量</td></tr><tr><td><b>用户</b></td><td>nonroot(uid 65532)</td></tr></table></div>