From 91e7ef56affca28f87e65a6dcda1b1bfad50551b Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 13 Oct 2026 01:57:34 +0800 Subject: [PATCH] settings, gateway, gui: a browser extension is listed among the web pages that may call magpie by its origin, chrome-extension:// and the like (#1051, SkyAerope on Discord) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What: Settings › Network and sharing › Web pages now takes a browser extension's origin besides http(s) ones: chrome-extension:// (Chromium, the id 32 letters a-p), moz-extension:// (Firefox's Internal UUID) and safari-web-extension:// (Safari). cleanOrigin takes only those three schemes, only with an id of that browser's shape, lower-cased and with a trailing "/" let go; a bare scheme, a wildcard, a path, a port, user info, a query or another browser's id shape is refused. The GUI maps the new refusal to the same message, which now names the extension form, in en/zh/zh-TW/ja/de, and a listed origin wraps instead of being cut (an extension's runs to 50-60 characters and was ellipsized at a 440px panel). The 401 a listed caller gets without a key names extensions too. Docs: gateway-routing.md, the settings field. Why: an extension without host_permissions (Sider and the like) is held to CORS; the gateway never answered its preflight, since its origin couldn't be listed. Nothing else in the access rules changes: corsGuard treats a listed extension exactly as a listed page (preflight answered, every call needs an enabled gateway key or gets 401, even on loopback), an unlisted extension passes with no CORS headers as before (foreignPage still only judges http/https), and lanGuard's rebound/Host checks, the allow list and every other route guard are untouched. The Origin each browser sends was checked, not guessed: real Chromium (below) sent Origin: chrome-extension://<32 a-p>; Firefox's is moz-extension:// (Gotify's and others' CORS docs list it); Safari's is safari-web-extension://, per Apple's developer forums (thread 654839), where an Apple engineer notes the uuid changes on each Safari launch, so a Safari listing lasts until it restarts (said in the doc). A content script's fetch carries the page's origin (MDN), so only extension pages, popups and workers are covered. Run, at 28aac86bc: - TestCleanExtensionOrigins (good ids, upper case, trailing slash; malformed, wildcard, bare scheme, path, port, userinfo, query, swapped id shapes) and TestCORSExtensionOrigin (through lanGuard: unlisted preflight/request get no CORS headers and the request runs as before; listed chrome and moz preflight 204 with the headers; keyed call 200 with Access-Control-Allow-Origin; keyless or wrong key 401 without reaching the vendor; another id still unlisted). Both fail on the old origins.go (the extension origin "is not an origin"). - go test ./internal/settings ./internal/gateway ./internal/gui: green. - gofmt -l clean; go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows: clean. - GUI: cors-origins (extended: an extension added upper-cased with a trailing slash is saved lower-cased and fits the panel, a malformed id and chrome-extension://* refused in the page's language), i18n-keys, gui-de, gui-ja, gui-zh-tw, allow-ips, lan-docker, chromium and webkit: green. cors-origins fails on the old app.js/app.css (the name was cut, the extension refusal untranslated). - Real use: an unpacked MV3 extension with no host_permissions, loaded in headless Chromium 1234 (playwright launchPersistentContext, --load-extension), fetched a sandbox gateway (lanGuard(New().Handler()) on 127.0.0.1:3591 under a temp HOME, fake vendor) from its service worker and its own page. Not listed: "Failed to fetch" in all four cases. Listed (typed upper-case with "/"): with the key, read 200 and the vendor's reply; without it, read the 401. Not tried: Firefox and Safari extensions for real (their origins are from the sources above), Edge/Brave, and the full magpie serve binary (the harness ran the gateway's own handler stack, not its background loops). --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/cors.go | 7 +- internal/gateway/cors_test.go | 102 +++++++++++++++++++++++ internal/gui/assets/app.css | 1 + internal/gui/assets/app.js | 4 +- internal/gui/assets/i18n.js | 8 +- internal/gui/tests/cors-origins.test.cjs | 33 ++++++-- internal/settings/origins.go | 42 +++++++++- internal/settings/origins_test.go | 46 ++++++++++ internal/settings/settings.go | 6 +- 10 files changed, 228 insertions(+), 23 deletions(-) diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 07fca0be3..0e9702798 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -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-` (`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/` 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. 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`). | [`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) | +| 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). 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://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (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`. `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/` 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. 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`). | [`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-`), 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) | diff --git a/internal/gateway/cors.go b/internal/gateway/cors.go index 9edeaad24..2534501f2 100644 --- a/internal/gateway/cors.go +++ b/internal/gateway/cors.go @@ -13,8 +13,9 @@ import ( "github.com/yetone/magpie/internal/settings" ) -// corsGuard lets the web pages the user listed in Settings › Gateway -// (settings.CORSOrigins, #1051) call the gateway from a browser: their +// corsGuard lets the web pages and browser extensions the user listed +// in Settings › Network (settings.CORSOrigins, #1051) call the gateway +// from a browser: their // preflight is answered, and their calls get the headers that let the page // read the reply. Such a call carries an enabled gateway key — a page is // not an agent the user started, and on loopback a call needs no key, so @@ -62,7 +63,7 @@ func corsGuard(next http.Handler) http.Handler { keyed := access.Caller(r.Context()).KeyID != "" || slices.ContainsFunc(callerKeys(r), func(k string) bool { _, ok := access.Authenticate(k); return ok }) if !keyed { - writeError(w, provider.Chat, http.StatusUnauthorized, "a web page calls magpie with a gateway key: create one in magpie's Gateway page and send it as Authorization: Bearer (or x-api-key)") + writeError(w, provider.Chat, http.StatusUnauthorized, "a web page or browser extension calls magpie with a gateway key: create one in magpie's Gateway page and send it as Authorization: Bearer (or x-api-key)") return } next.ServeHTTP(w, r) diff --git a/internal/gateway/cors_test.go b/internal/gateway/cors_test.go index 9fa0ea5d2..6743e3153 100644 --- a/internal/gateway/cors_test.go +++ b/internal/gateway/cors_test.go @@ -289,3 +289,105 @@ func TestForeignPagesRefused(t *testing.T) { t.Errorf("usemagpie.ai's Omarchy theme: %d %s", w.Code, w.Body) } } + +// A browser extension the user listed by its origin (#1051, SkyAerope on +// Discord: an extension such as Sider, without host permissions, is held +// to CORS like a page) is treated as a listed web page is, no more: its +// preflight is answered, its keyed call reads the reply, and a call +// without a gateway key is refused 401. An extension not listed is +// answered as before — no CORS headers, so only one that holds host +// permissions (and doesn't enforce CORS) reads anything. +func TestCORSExtensionOrigin(t *testing.T) { + fresh(t) + var hits atomic.Int64 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`) + })) + defer up.Close() + if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil { + t.Fatal(err) + } + secret, err := access.Update("add-key", access.Change{Name: "Extension"}) + if err != nil { + t.Fatal(err) + } + const ext = "chrome-extension://abcdefghijklmnopabcdefghijklmnop" + const other = "chrome-extension://ponmlkjihgfedcbaponmlkjihgfedcba" + const fox = "moz-extension://e0b5d7c7-c079-484b-8825-44d261383cb6" + srv := lanGuard(New().Handler()) + do := func(method, origin, key string) *httptest.ResponseRecorder { + t.Helper() + var body io.Reader + if method == "POST" { + body = strings.NewReader(chatReq) + } + r := httptest.NewRequest(method, "/v1/chat/completions", body) + r.RemoteAddr = "127.0.0.1:50123" + r.Host = "127.0.0.1:3425" + r.Header.Set("Origin", origin) + r.Header.Set("Sec-Fetch-Mode", "cors") + r.Header.Set("User-Agent", "Mozilla/5.0 Chrome/140.0") + if method == "OPTIONS" { + r.Header.Set("Access-Control-Request-Method", "POST") + r.Header.Set("Access-Control-Request-Headers", "authorization, content-type") + } else { + r.Header.Set("Content-Type", "application/json") + } + if key != "" { + r.Header.Set("Authorization", "Bearer "+key) + } + w := httptest.NewRecorder() + srv.ServeHTTP(w, r) + return w + } + // not listed: no CORS headers, as before; a web page listed doesn't list it + s := settings.Load() + s.CORSOrigins = []string{"http://localhost:3000"} + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + if w := do("OPTIONS", ext, ""); w.Code == http.StatusNoContent || w.Header().Get("Access-Control-Allow-Origin") != "" { + t.Fatalf("unlisted extension's preflight: %d %v", w.Code, w.Header()) + } + if w := do("POST", ext, ""); w.Code != http.StatusOK || w.Header().Get("Access-Control-Allow-Origin") != "" { + t.Fatalf("unlisted extension, as before: %d %v %s", w.Code, w.Header(), w.Body) + } + + // listed, written as the user might copy it + if s.CORSOrigins, err = settings.CleanOrigins([]string{"http://localhost:3000", "CHROME-EXTENSION://ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP/", fox}); err != nil { + t.Fatal(err) + } + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + for _, o := range []string{ext, fox} { + w := do("OPTIONS", o, "") + if w.Code != http.StatusNoContent || w.Header().Get("Access-Control-Allow-Origin") != o || + w.Header().Get("Access-Control-Allow-Headers") != "authorization, content-type" || !strings.Contains(w.Header().Get("Access-Control-Allow-Methods"), "POST") { + t.Errorf("%s preflight: %d %v", o, w.Code, w.Header()) + } + if w := do("POST", o, secret); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "ok") || w.Header().Get("Access-Control-Allow-Origin") != o { + t.Errorf("%s with its key: %d %v %s", o, w.Code, w.Header(), w.Body) + } + } + n := hits.Load() + // a listed extension needs a gateway key, as a listed page does + if w := do("POST", ext, ""); w.Code != http.StatusUnauthorized || w.Header().Get("Access-Control-Allow-Origin") != ext || !strings.Contains(w.Body.String(), "gateway key") { + t.Errorf("listed extension without a key: %d %v %s", w.Code, w.Header(), w.Body) + } + if w := do("POST", ext, "not-a-key"); w.Code != http.StatusUnauthorized { + t.Errorf("listed extension with a wrong key: %d %s", w.Code, w.Body) + } + if hits.Load() != n { + t.Fatal("a keyless call from a listed extension reached the vendor") + } + // another extension is still not listed + if w := do("OPTIONS", other, ""); w.Header().Get("Access-Control-Allow-Origin") != "" { + t.Errorf("another extension's preflight: %d %v", w.Code, w.Header()) + } + if w := do("POST", other, secret); w.Header().Get("Access-Control-Allow-Origin") != "" { + t.Errorf("another extension: %d %v", w.Code, w.Header()) + } +} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index a35ac8579..ad7125e99 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2996,6 +2996,7 @@ input.words.compact-num { flex: none; width: 76px; font-variant-numeric: tabular .row.pref.rule-row { flex-wrap: wrap; row-gap: 8px; } .row.pref.rule-row .who { flex: 1 1 100%; } .row.pref.rule-row .sub { white-space: normal; } +.row.pref.cors-origin .name { white-space: normal; overflow-wrap: anywhere; } /* a kind of personal data, under Mask personal data */ .row.pref.redact-kind .who { padding-left: 14px; min-width: 0; } .row.pref.redact-kind .sub { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index cd1412c50..9366ce289 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -22434,7 +22434,7 @@ let corsDraft = { value: "", err: "" }; // page's language function corsSays(m) { if (/wildcard/.test(m)) return t("Name each origin: a wildcard would let every web page use magpie"); - if (/is not an origin/.test(m)) return t("Write an origin as http://localhost:3000 or https://app.example.com"); + if (/is not an (extension's )?origin/.test(m)) return t("Write an origin as http://localhost:3000 or https://app.example.com, or a browser extension's as chrome-extension://, moz-extension:// or safari-web-extension:// followed by its ID"); return t(m); } function renderCORS(s) { @@ -22467,7 +22467,7 @@ function renderCORS(s) { r.append(who, val); box.append(r); for (const o of origins) { - const row = el("div", "row pref"); + const row = el("div", "row pref cors-origin"); // an extension's id runs long: wrapped, never cut const w = el("div", "who"); w.append(el("div", "name", o)); const x = el("button", "text", t("Remove")); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 19f4ebc6c..d0b54659b 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1898,7 +1898,7 @@ const I18N = { "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", + "Write an origin as http://localhost:3000 or https://app.example.com, or a browser extension's as chrome-extension://, moz-extension:// or safari-web-extension:// followed by its ID": "来源格式如 http://localhost:3000 或 https://app.example.com;浏览器插件写作 chrome-extension://、moz-extension:// 或 safari-web-extension:// 加上它的 ID", "{name} removed": "已移除 {name}", "Add": "添加", "{name} added": "已添加 {name}", @@ -6356,7 +6356,7 @@ const I18N = { "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", + "Write an origin as http://localhost:3000 or https://app.example.com, or a browser extension's as chrome-extension://, moz-extension:// or safari-web-extension:// followed by its ID": "來源格式如 http://localhost:3000 或 https://app.example.com;瀏覽器擴充功能寫作 chrome-extension://、moz-extension:// 或 safari-web-extension:// 加上它的 ID", "{name} removed": "已移除 {name}", "Add": "新增", "{name} added": "已新增 {name}", @@ -10792,7 +10792,7 @@ const I18N = { "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 の形式で入力してください", + "Write an origin as http://localhost:3000 or https://app.example.com, or a browser extension's as chrome-extension://, moz-extension:// or safari-web-extension:// followed by its ID": "オリジンは http://localhost:3000 や https://app.example.com の形式で、ブラウザー拡張機能は chrome-extension://、moz-extension://、safari-web-extension:// のあとに ID を続けて入力してください", "{name} removed": "{name} を削除しました", "Add": "追加", "{name} added": "{name} を追加しました", @@ -15247,7 +15247,7 @@ const I18N = { "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", + "Write an origin as http://localhost:3000 or https://app.example.com, or a browser extension's as chrome-extension://, moz-extension:// or safari-web-extension:// followed by its ID": "Eine Herkunft wird wie http://localhost:3000 oder https://app.example.com geschrieben, die einer Browsererweiterung als chrome-extension://, moz-extension:// oder safari-web-extension:// mit ihrer ID", "{name} removed": "{name} entfernt", "Add": "Hinzufügen", "{name} added": "{name} hinzugefügt", diff --git a/internal/gui/tests/cors-origins.test.cjs b/internal/gui/tests/cors-origins.test.cjs index 1e34b9c41..70194a922 100644 --- a/internal/gui/tests/cors-origins.test.cjs +++ b/internal/gui/tests/cors-origins.test.cjs @@ -3,7 +3,9 @@ // http://localhost:3000 couldn't read the gateway's answers): Settings › // Network lists them by origin. One is added from a field and its Add // button (or Enter), saved as the gateway cleaned it, and taken away with -// its Remove; a wildcard or a URL that isn't an origin is refused, said in +// its Remove; a browser extension is added by its origin +// (chrome-extension://, SkyAerope on Discord); a wildcard, a URL that +// isn't an origin or an extension id no browser gives is refused, said in // the page's language, and nothing is saved. At a 440px panel every row // fits, and no click moves the page. English and Chinese, Chromium and // WebKit; no backend, the API is faked here. @@ -37,9 +39,17 @@ function clean(list) { const out = []; for (const raw of list) { if (raw.includes("*")) return { error: `"${raw}": name each origin; a wildcard would let every web page use magpie` }; + const ext = /^(chrome-extension|moz-extension|safari-web-extension):\/\/(.*?)\/?$/.exec(raw.trim().toLowerCase()); + if (ext) { + const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; + if (!(ext[1] === "chrome-extension" ? /^[a-p]{32}$/ : uuid).test(ext[2])) return { error: `"${raw}" is not an extension's origin: write it as ${ext[1]}://, the ID as the browser's extensions page shows it` }; + const o = ext[1] + "://" + ext[2]; + if (!out.includes(o)) out.push(o); + continue; + } let u; try { u = new URL(raw); } catch { u = null; } - if (!u || !/^https?:$/.test(u.protocol) || (u.pathname !== "/" && u.pathname !== "")) return { error: `"${raw}" is not an origin: write it as http://localhost:3000 or https://app.example.com` }; + if (!u || !/^https?:$/.test(u.protocol) || (u.pathname !== "/" && u.pathname !== "")) return { error: `"${raw}" is not an origin: write it as http://localhost:3000 or https://app.example.com, or an extension's as chrome-extension://` }; if (!out.includes(u.origin)) out.push(u.origin); } return { origins: out }; @@ -77,7 +87,7 @@ const words = { head: "Web pages", name: "Web pages that may call magpie", add: "Add", remove: "Remove", sub: "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", wildcard: "Name each origin: a wildcard would let every web page use magpie", - notOrigin: "Write an origin as http://localhost:3000 or https://app.example.com", + notOrigin: "Write an origin as http://localhost:3000 or https://app.example.com, or a browser extension's as chrome-extension://, moz-extension:// or safari-web-extension:// followed by its ID", }, zh: { head: "网页", name: "允许调用 magpie 的网页", add: "添加", remove: "移除", @@ -165,15 +175,24 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await box.locator(".row:not(.rule-row) .name", { hasText: "https://app.example.com" }).waitFor(); assert.deepEqual(posts.at(-1), ["http://localhost:3000", "https://app.example.com"]); await fits(); + // a browser extension, by its origin as copied from its page + const ext = "chrome-extension://abcdefghijklmnopabcdefghijklmnop"; + await row.locator("input").fill(ext.toUpperCase() + "/"); + before = await scroll(); + await row.locator("button", { hasText: w.add }).click(); + await box.locator(".row:not(.rule-row) .name", { hasText: ext }).waitFor(); + assert.deepEqual(posts.at(-1), ["http://localhost:3000", "https://app.example.com", ext.toUpperCase() + "/"]); + assert.equal(await scroll(), before, "adding an extension moved the page"); + await fits(); // refused, in the page's language, and nothing saved - for (const [bad, says] of [["*", w.wildcard], ["localhost:4000/v1", w.notOrigin]]) { + for (const [bad, says] of [["*", w.wildcard], ["localhost:4000/v1", w.notOrigin], ["chrome-extension://abc", w.notOrigin], ["chrome-extension://*", w.wildcard]]) { await row.locator("input").fill(bad); before = await scroll(); await row.locator("button", { hasText: w.add }).click(); await page.waitForFunction((s) => document.querySelector("#corsList .rule-row .sub.err")?.textContent.trim() === s, says); assert.equal(await row.locator("input").inputValue(), bad, "what the user wrote stays, to be corrected"); - assert.equal(await box.locator(".row:not(.rule-row)").count(), 2); + assert.equal(await box.locator(".row:not(.rule-row)").count(), 3); assert.equal(await scroll(), before, "a refusal moved the page"); await fits(); } @@ -182,8 +201,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const gone = box.locator(".row:not(.rule-row)").filter({ hasText: "http://localhost:3000" }); before = await scroll(); await gone.locator("button", { hasText: w.remove }).click(); - await page.waitForFunction(() => document.querySelectorAll("#corsList .row:not(.rule-row)").length === 1); - assert.deepEqual(posts.at(-1), ["https://app.example.com"]); + await page.waitForFunction(() => document.querySelectorAll("#corsList .row:not(.rule-row)").length === 2); + assert.deepEqual(posts.at(-1), ["https://app.example.com", "chrome-extension://abcdefghijklmnopabcdefghijklmnop"]); assert.equal(await scroll(), before, "Remove moved the page"); assert.equal((await row.locator(".sub").textContent()).trim(), w.sub, "a save clears the refusal"); diff --git a/internal/settings/origins.go b/internal/settings/origins.go index a71580914..3c062d80f 100644 --- a/internal/settings/origins.go +++ b/internal/settings/origins.go @@ -4,15 +4,18 @@ import ( "fmt" "net" "net/url" + "regexp" "slices" "strings" ) // CleanOrigins is the web origins a user typed for CORSOrigins, as a // browser's Origin header spells them: scheme://host[:port], lower-cased, -// with no path and the scheme's default port left out. Only http and -// https are origins; "*" is refused, since it would let every web page the -// user opens spend their subscriptions. +// with no path and the scheme's default port left out. http and https are +// origins, and so is a browser extension's page by its id (#1051, +// SkyAerope: an extension without host permissions is held to CORS like a +// page), as extensionIDs spells them; "*" is refused, since it would let +// every web page or extension the user has spend their subscriptions. func CleanOrigins(in []string) ([]string, error) { var out []string for _, raw := range in { @@ -35,10 +38,13 @@ func cleanOrigin(raw string) (string, error) { if strings.Contains(raw, "*") { return "", fmt.Errorf("%q: name each origin; a wildcard would let every web page use magpie", raw) } + if o, ok, err := extensionOrigin(raw); ok { + return o, err + } u, err := url.Parse(strings.TrimSuffix(raw, "/")) if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" { - return "", fmt.Errorf("%q is not an origin: write it as http://localhost:3000 or https://app.example.com", raw) + return "", fmt.Errorf("%q is not an origin: write it as http://localhost:3000 or https://app.example.com, or an extension's as chrome-extension://", raw) } host, port := strings.ToLower(u.Hostname()), u.Port() if (u.Scheme == "http" && port == "80") || (u.Scheme == "https" && port == "443") { @@ -52,3 +58,31 @@ func cleanOrigin(raw string) (string, error) { } return u.Scheme + "://" + host, nil } + +// extensionIDs is the host each browser's extension origin has, as it +// sends it in Origin for a fetch from the extension's own pages, popup or +// service worker (a content script's fetch carries the page's origin): +// Chromium's chrome-extension://, the id 32 letters a–p; Firefox's +// moz-extension://, its per-install Internal UUID; Safari's +// safari-web-extension://, which Safari picks anew on each launch. +var extensionIDs = map[string]*regexp.Regexp{ + "chrome-extension": regexp.MustCompile(`^[a-p]{32}$`), + "moz-extension": regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`), + "safari-web-extension": regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`), +} + +// extensionOrigin is raw as an extension's origin, lower-cased, with a +// trailing "/" let go; ok says raw names an extension scheme at all, and +// then err says when its id isn't one that browser gives. +func extensionOrigin(raw string) (o string, ok bool, err error) { + scheme, rest, found := strings.Cut(strings.ToLower(raw), "://") + id := extensionIDs[scheme] + if !found || id == nil { + return "", false, nil + } + rest = strings.TrimSuffix(rest, "/") + if !id.MatchString(rest) { + return "", true, fmt.Errorf("%q is not an extension's origin: write it as %s://, the ID as the browser's extensions page shows it", raw, scheme) + } + return scheme + "://" + rest, true, nil +} diff --git a/internal/settings/origins_test.go b/internal/settings/origins_test.go index 7ade3a72b..e928f7beb 100644 --- a/internal/settings/origins_test.go +++ b/internal/settings/origins_test.go @@ -22,3 +22,49 @@ func TestCleanOrigins(t *testing.T) { } } } + +// A browser extension's page is listed by its origin, as the browser +// sends it (#1051, SkyAerope on Discord: chrome-extension:// couldn't +// be added): Chromium's id of 32 letters a–p, Firefox's and Safari's +// UUID, however the user cased it or with a trailing "/". A bare scheme, +// a wildcard, an id that browser never gives, a path or a port is refused. +func TestCleanExtensionOrigins(t *testing.T) { + const chrome = "abcdefghijklmnopabcdefghijklmnop" + const uuid = "e0b5d7c7-c079-484b-8825-44d261383cb6" + got, err := CleanOrigins([]string{ + "chrome-extension://" + chrome, + " Chrome-Extension://" + strings.ToUpper(chrome) + "/ ", + "moz-extension://" + strings.ToUpper(uuid) + "/", + "safari-web-extension://" + uuid, + }) + if err != nil { + t.Fatal(err) + } + want := []string{"chrome-extension://" + chrome, "moz-extension://" + uuid, "safari-web-extension://" + uuid} + if strings.Join(got, " ") != strings.Join(want, " ") { + t.Fatalf("%v, want %v", got, want) + } + for _, bad := range []string{ + "chrome-extension://", "chrome-extension:///", "chrome-extension://*", "chrome-extension://" + chrome[:31] + "*", + "chrome-extension://" + chrome[:31], // too short + "chrome-extension://" + chrome + "a", // too long + "chrome-extension://" + chrome[:31] + "q", // not a–p + "chrome-extension://" + chrome + "/popup.html", // a page, not an origin + "chrome-extension://" + chrome + ":80", + "chrome-extension://u@" + chrome, + "chrome-extension://" + chrome + "?x=1", + "chrome-extension://" + uuid, // Firefox's id under Chrome's scheme + "moz-extension://" + chrome, // and Chrome's under Firefox's + "moz-extension://{" + uuid + "}", // braces are not in the origin + "moz-extension://" + strings.ReplaceAll(uuid, "-", ""), + "moz-extension://" + uuid[:35] + "g", + "safari-web-extension://" + uuid + "/x", + "moz-extension://*", + "safari-web-extension://", + "ms-browser-extension://" + chrome, + } { + if o, err := CleanOrigins([]string{bad}); err == nil { + t.Errorf("%q taken as %v", bad, o) + } + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index e0daa0ce0..1f9b71d5b 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -91,8 +91,10 @@ type Settings struct { // named caller keys. LANKey is retained for older Magpie versions. LAN bool `json:"lan,omitempty"` LANKey string `json:"lanKey,omitempty"` - // CORSOrigins are the web pages (scheme://host[:port]) whose scripts - // may call the gateway from a browser (#1051): a preflight from one is + // CORSOrigins are the web pages (scheme://host[:port]) and browser + // extensions (chrome-extension://, moz-extension://, + // safari-web-extension://) whose scripts may call the gateway + // from a browser (#1051): a preflight from one is // answered, and its calls carry the CORS headers that let it read the // reply, each with an enabled gateway key. None by default: a page // gets no CORS headers, as before.