diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 36f35af3a..ace43aa71 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -15,7 +15,7 @@ three. | 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), and `watchGateway` looks at it again every 15 s (`gatewayWatch`). A magpie of another version there (`otherServes` in `gateway_older.go`) is told the page as `gatewayOther` in `/api/state` and said over the Agents list (`gatewaySkewLine` in `plugins/gateway/client.js`), in the panel and the window: pi got 404 for a model the newer app had written it while an older copy of the app kept the gateway, and only the Gateway page said so (matrix0487 on Discord). An older released copy of the app (`serves` app or tray, with a pid) is this app's own predecessor: once its `/v1/magpie/concurrency` says nothing is in flight (`gateway.ServedBusy`; unknown is never idle) the app quits it as the Gateway page's button does (`quitMagpieOnPort`, a magpie only) and serves the gateway, so no stream is cut; at most three times a run (`replaceMost`), and a quit that fails is left to the button. Any other (magpie serve or the service, `magpie web`, a TUI, a newer magpie, a build of its own) is left running, with what to do; a dev build of this magpie says nothing. A request that starts between the idle read and the quit gets the older app's short drain. See `TestAppReplacesItsOlderGatewayOnceIdle`, `TestGatewaySkewOfAnotherIsSaidNotQuit` and `gateway-skew.test.cjs`. `magpie serve` (the service's, launchd's `com.yetone.magpie.serve` or systemd's) does the same beside a magpie serving or another program holding the port: before it moves or starts anything (`startUp`), it waits, looking every 15 s, and serves once the port is free (`awaitGatewayFree` in [`serve_wait.go`](../../internal/cli/serve_wait.go); `--web` excepted, which shows the other one). Before, it ran the start-up moves, the plugin host and every account's model fetch, failed to bind, exited 1 and was started again by the service, 6,035 times in two days with a 279MB serve.log and requests 504 behind it (#4938, `TestServeWaitsForTheGatewayBeforeStartingUp`). `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), [`gateway_older.go`](../../internal/gui/gateway_older.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) | | Settings from the terminal | `POST /api/settings` saves through `settingsapi.Apply` (`internal/settingsapi`, outside the GUI so the `nogui` build has it): the carry of keys a page leaves out (`Merge`), the vision, image and searcher checks, `settings.Save`'s own checks, and `catalog.Touched`. `magpie settings list\|get\|set\|reset` (#4745) builds the same body with `settingsapi.Body` (the whole file with one key changed, so a key the save keeps when it isn't sent is set even to off) and calls the same `Apply`; a refused value writes nothing. `settingsapi.Keys` names what the save writes; `TestKeysAreWhatTheSaveWrites` fails when a field of `settings.Settings` is saved without it, `TestSettingsCLISetsWhatTheWindowSaves` when a key the page's `savePrefs` sends isn't one, and `TestEveryRouteHasACommandOrIsNamed` when an `/api` route has neither a command nor a reason in `notYet` (`internal/cli/settings_parity_test.go`). The running app's in-process follow-ups (fonts, Dock, tray menu, alerts, language, update check) run only from the window's save; a change from the terminal is read from the file. | [`internal/settingsapi/settingsapi.go`](../../internal/settingsapi/settingsapi.go), [`settings_cli.go`](../../internal/cli/settings_cli.go) | -| Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Added to a phone's home screen the page opens as an app of its own, with no browser bars (ninja_s6114 on Discord): `index.html` names `manifest.json` (display standalone), an apple-touch-icon and the iOS meta tags, the status bar keeps its own ground (`default`), and its theme colours match only `(display-mode: standalone)`, so a browser's tab and the app's windows take none. `webGuard` serves those three files (`webAppFiles`: the manifest, `icons/apple-touch-icon.png`, `icons/icon-512.png`) without the key, to GET and HEAD at those exact paths alone, as a home screen may ask without the cookie; see `TestWebAppAddsToHomeScreen` and `web-app-standalone.test.cjs`. Gateway mode shows every page but Agents on a machine that is only a gateway (`GATEWAY_HIDES`); the Library has its MCP servers and the MCP router alone, for other computers' apps to reach with a gateway key (treeman_26897 on Discord, `gateway-mode.test.cjs`, `library-mcp-agentless.test.cjs`). `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; never an event stream, which gzip would hold back until its buffer fills); 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, always as a request from another machine (`gateway.FromPagePort`, the `X-Magpie-Page-Port` mark: `local` is false for it, from loopback too and under `MAGPIE_TRUST_PROXY`, so magpie must be shared and the request carry an enabled gateway key), since a raw TCP forward or a proxy that adds no forwarding header reaches this port from loopback looking like an agent here (reported privately by Coffemon); agents here use the gateway's own port. `Server.Front` (lanGuard over Handler) serves them in process when this process serves the gateway, or `toGateway`, a reverse proxy to `gateway.URL()`, when another magpie does; it keeps the Host, the forwarding headers and the mark, adds X-Forwarded-For for a peer that isn't loopback, and the peer's loopback address as X-Forwarded-For when none came, so a gateway of an older magpie that doesn't know the mark still asks for a key. `lanGuard` moves the mark into the request's context and takes the header off, so it never goes upstream. The page itself calls no client route. See `TestWebOnePortServedHere`, `TestWebOnePortServedElsewhere`, `TestWebOnePortAgentsHereUseTheGatewayPort`, `TestPagePortMarkIsNeverLocal` and `TestClientPathCoversHandler`. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go), [`oneport.go`](../../internal/gateway/oneport.go) | +| Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Added to a phone's home screen the page opens as an app of its own, with no browser bars (ninja_s6114 on Discord): `index.html` names `manifest.json` (display standalone), an apple-touch-icon and the iOS meta tags, the status bar keeps its own ground (`default`), and its theme colours match only `(display-mode: standalone)`, so a browser's tab and the app's windows take none. `webGuard` serves those three files (`webAppFiles`: the manifest, `icons/apple-touch-icon.png`, `icons/icon-512.png`) without the key, to GET and HEAD at those exact paths alone, as a home screen may ask without the cookie; see `TestWebAppAddsToHomeScreen` and `web-app-standalone.test.cjs`. The cookie is SameSite=Lax, which a browser sends with any request from the same site, other ports and sibling subdomains included, so `webOwnPage` answers `/api` for the page's own origin only: a write goes through net/http's `CrossOriginProtection` (Sec-Fetch-Site same-origin or none; from a browser without it, an Origin that is absent or names the Host or `MAGPIE_PUBLIC_URL`), and any request whose Sec-Fetch-Site says another origin sent it is refused, a GET too; see `TestWebAPIAnswersItsOwnPageOnly`. The desktop window's `/api` is in-process with no cookie and isn't held to it. Gateway mode shows every page but Agents on a machine that is only a gateway (`GATEWAY_HIDES`); the Library has its MCP servers and the MCP router alone, for other computers' apps to reach with a gateway key (treeman_26897 on Discord, `gateway-mode.test.cjs`, `library-mcp-agentless.test.cjs`). `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; never an event stream, which gzip would hold back until its buffer fills); 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, always as a request from another machine (`gateway.FromPagePort`, the `X-Magpie-Page-Port` mark: `local` is false for it, from loopback too and under `MAGPIE_TRUST_PROXY`, so magpie must be shared and the request carry an enabled gateway key), since a raw TCP forward or a proxy that adds no forwarding header reaches this port from loopback looking like an agent here (reported privately by Coffemon); agents here use the gateway's own port. `Server.Front` (lanGuard over Handler) serves them in process when this process serves the gateway, or `toGateway`, a reverse proxy to `gateway.URL()`, when another magpie does; it keeps the Host, the forwarding headers and the mark, adds X-Forwarded-For for a peer that isn't loopback, and the peer's loopback address as X-Forwarded-For when none came, so a gateway of an older magpie that doesn't know the mark still asks for a key. `lanGuard` moves the mark into the request's context and takes the header off, so it never goes upstream. The page itself calls no client route. See `TestWebOnePortServedHere`, `TestWebOnePortServedElsewhere`, `TestWebOnePortAgentsHereUseTheGatewayPort`, `TestPagePortMarkIsNeverLocal` and `TestClientPathCoversHandler`. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go), [`oneport.go`](../../internal/gateway/oneport.go) | | The app's page in a browser | Settings › Network and sharing › Browser access (`renderWebPage` in `plugins/gateway/settings.js`, drawn with the Web pages rows) has the app serve its own page to a browser while it runs, so a tunnel (Cloudflare Tunnel, SSH) or a computer on the network can reach it without `magpie web` kept running in a terminal (jiakun_zhao on X). Off, This computer (`127.0.0.1`, which a tunnel's service points at) or Local network (every address; a "Not encrypted" row without `--tls-cert`). It is `magpie web`'s page and guard, not a second kind: `startAppPage` (from `Run`, after `startBackend`) serves `webServed` over a `Handler` of its own, whose `Windows` is `appWebHost` (a browser tab for `isWeb`, but not `ownWeb`, so the app's windows aren't taken for `magpie web`'s: `webPage` and gateway mode stay the app's; quitting quits the app, and a restart to update from it brings back the windows the app has up, `restartFrom`). The key is always asked for: no mode serves without it. It lives with the mode and port in `web-page.json` beside settings.json (0600, never in settings.json, so sync and backup don't carry it), is made the first time the page is turned on, kept across restarts (a browser's cookie stays good), and replaced by New key, which turns away every browser signed in with the old one (the guard is swapped atomically, `appPage.cur`). A file that can't be read, or names no known mode, is off and says why; Settings rewrites it only given a whole choice. A port another program holds (`magpie web`; the magpie before a restart to update) is said and tried again every 4 s (`appPageRetry`); the port must be 1024 up and not the gateway's. `GET/POST /api/web-page` are on the app's own windows' API only, never a browser's, so a browser on the page can neither read the key it came in without nor turn the page off under itself. `magpie web` on the port the app serves prints the app's link and opens it rather than starting a second (`gui.AppPage`, `samePort`). Sessions are warmed once a process however many `Handler`s there are (`warmOnce`). See `TestAppPageServesOnlyWithItsKey`, `TestAppPageWaitsForABusyPort`, `TestAppPageUnreadFileServesNothing`, `TestAppPageTurnsDownBadChoices`, `TestAppPageBrowserIsATab` and `browser-access.test.cjs`. | [`apppage.go`](../../internal/gui/apppage.go), [`web_cli.go`](../../internal/cli/web_cli.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//` (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; a client whose User-Agent names only an HTTP library, a runtime or an API SDK (`usage.IsLibrary`: curl, Bun, python-httpx, Go-http-client, OpenAI/Python), or nothing (`other`), is no agent and goes on one card, `scripts`, named Scripts with its libraries listed, read from each route's kept agent so older history folds too, while the Usage page's Agents list keeps each by its own name (theforeveriris on X, `context_scripts_test.go`, `context-scripts.test.cjs`); clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory, else the request archive's copy masked the same way, with a 404 saying why there is none (`archive`: off, missing, cut, unread; `context_archive.go`), and its Reply the reply from `/api/context/reply` (`openCtxText`, in `ctxtext.js`, `context-text.test.cjs`), 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, or drawn at once from boot.js's `sideGateway`; on a page other machines open, `magpie web`, it is `MAGPIE_PUBLIC_URL` while they are let in, as the Gateway page's address and About's Gateway URL are, noahhrreion on Discord; a port applied in Settings redraws it), 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) | diff --git a/internal/gui/web.go b/internal/gui/web.go index 12ff3c8fd..74787d686 100644 --- a/internal/gui/web.go +++ b/internal/gui/web.go @@ -349,7 +349,55 @@ func webServed(port, key string, keep time.Duration, page http.Handler) http.Han // 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 { - return webCompressed(webGuard("magpie_web_"+port, key, keep, page)) + return webCompressed(webGuard("magpie_web_"+port, key, keep, webOwnPage(page))) +} + +// webOwnPage turns away a request for /api that another page sent with +// the page's cookie. The cookie is SameSite=Lax, so a browser sends it +// with any request one site sends another, and a site is the registrable +// domain without the port: a page on another port of 127.0.0.1 or of the +// LAN address, or on a sibling name behind the same reverse proxy, could +// POST a stdio MCP server to /api/library/servers/save as text/plain in +// no-cors mode and start it with /api/library/mcp/check, which is code run +// as the user. Only the page itself may write: a write (any method but +// GET, HEAD and OPTIONS) is judged by net/http's CrossOriginProtection, +// which takes the browser's Sec-Fetch-Site (same-origin, or none for what +// the user did) and, from a browser too old to send it, an Origin that is +// absent or names the request's own Host or MAGPIE_PUBLIC_URL. A read is +// turned away too when the browser says another origin sent it, so that +// no GET route that does something (an import read once, a sign-in +// started) is any page's to call, whether or not it answers. +// +// The desktop window's /api is served in the process, over no port, and +// has no cookie for another page to borrow, so this is for the browser's +// page alone. +func webOwnPage(next http.Handler) http.Handler { + cop := http.NewCrossOriginProtection() + if u, err := url.Parse(gateway.PublicURL()); err == nil && u.Host != "" && (u.Scheme == "http" || u.Scheme == "https") { + // behind a proxy that passes on a Host of its own, the page's + // address is the one the user named + if err := cop.AddTrustedOrigin(u.Scheme + "://" + u.Host); err != nil { + log.Printf("magpie web: MAGPIE_PUBLIC_URL %s is no origin: %v", u, err) + } + } + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + if !strings.HasPrefix(r.URL.Path, "/api/") { + next.ServeHTTP(rw, r) + return + } + err := cop.Check(r) + if err == nil { + if site := r.Header.Get("Sec-Fetch-Site"); site != "" && site != "same-origin" && site != "none" { + err = errors.New("Sec-Fetch-Site " + site) + } + } + if err != nil { + log.Printf("magpie web: turned away %s %s from another page (Origin %q): %v", r.Method, r.URL.Path, r.Header.Get("Origin"), err) + http.Error(rw, "magpie's API answers magpie's own page only", http.StatusForbidden) + return + } + next.ServeHTTP(rw, r) + }) } // webCompressed gzips what `magpie web` sends a browser that takes it: the diff --git a/internal/gui/web_ownpage_test.go b/internal/gui/web_ownpage_test.go new file mode 100644 index 000000000..47494b286 --- /dev/null +++ b/internal/gui/web_ownpage_test.go @@ -0,0 +1,79 @@ +package gui + +import ( + "net/http" + "testing" +) + +// A page on another port of the same host, on another port of the LAN +// address, or on a sibling name behind the same proxy is the same site, so +// the browser sends it the page's SameSite=Lax cookie: its "simple" POST +// (text/plain, no-cors) to /api/library/servers/save, then +// /api/library/mcp/check, would start an MCP server of its own as the +// user. Through the whole chain `magpie web` serves, with the page's +// cookie, every such request is turned away, and the page's own still +// reach the API. +func TestWebAPIAnswersItsOwnPageOnly(t *testing.T) { + onePortHome(t) + const lo = "127.0.0.1:50001" + noCors := []string{"Sec-Fetch-Mode", "no-cors", "Sec-Fetch-Dest", "empty"} + marks := func(site string, hdr ...string) []string { + if site != "" { + hdr = append(hdr, "Sec-Fetch-Site", site) + } + return append(hdr, noCors...) + } + call := func(name string, want bool, method, target, host string, hdr ...string) { + t.Helper() + var reached bool + h := onePortPage(&reached) + w := onePortCall(t, h, method, target, lo, host, onePortWebKey, hdr...) + if reached != want || !want && w.Code != http.StatusForbidden { + t.Errorf("%s: %s %s under Host %s: %d, reached %v, want reached %v: %s", name, method, target, host, w.Code, reached, want, w.Body.String()) + } + } + const save, check = "/api/library/servers/save", "/api/library/mcp/check" + for _, path := range []string{save, check} { + // another port of 127.0.0.1 + call("same-site Origin on another port", false, "POST", path, "127.0.0.1:3430", marks("same-site", "Origin", "http://127.0.0.1:8080")...) + call("cross-port Origin from a browser without Sec-Fetch-Site", false, "POST", path, "127.0.0.1:3430", marks("", "Origin", "http://127.0.0.1:8080")...) + call("localhost on another port", false, "POST", path, "localhost:3430", marks("same-site", "Origin", "http://localhost:5173")...) + // another port of the LAN address + call("the LAN address on another port", false, "POST", path, "192.168.1.20:3430", marks("same-site", "Origin", "http://192.168.1.20:8080")...) + call("the LAN address on another port, an old browser", false, "POST", path, "192.168.1.20:3430", marks("", "Origin", "http://192.168.1.20:8080")...) + // a sibling name behind the same reverse proxy + call("a sibling subdomain", false, "POST", path, "magpie.example.com", marks("same-site", "Origin", "https://blog.example.com")...) + call("a sibling subdomain, an old browser", false, "POST", path, "magpie.example.com", marks("", "Origin", "https://blog.example.com")...) + call("another site", false, "POST", path, "127.0.0.1:3430", marks("cross-site", "Origin", "https://evil.example")...) + // a sandboxed frame or a local file + call("Origin null", false, "POST", path, "127.0.0.1:3430", marks("cross-site", "Origin", "null")...) + call("Origin null, an old browser", false, "POST", path, "127.0.0.1:3430", marks("", "Origin", "null")...) + // what the Origin leaves out the browser still says + call("no Origin, Sec-Fetch-Site same-site", false, "POST", path, "127.0.0.1:3430", marks("same-site")...) + call("no Origin, Sec-Fetch-Site cross-site", false, "POST", path, "127.0.0.1:3430", marks("cross-site")...) + } + // a read another page sends: an , a link, a form's GET + call("a GET from another port", false, "GET", "/api/import/x", "127.0.0.1:3430", marks("same-site")...) + call("a GET from a sibling subdomain", false, "GET", "/api/import/x", "magpie.example.com", "Sec-Fetch-Site", "same-site", "Sec-Fetch-Dest", "image") + call("a link from another site", false, "GET", "/api/import/x", "127.0.0.1:3430", "Sec-Fetch-Site", "cross-site", "Sec-Fetch-Dest", "document", "Sec-Fetch-Mode", "navigate") + call("a preflight from another port", false, "OPTIONS", save, "127.0.0.1:3430", "Origin", "http://127.0.0.1:8080", "Sec-Fetch-Site", "same-site") + + // the page's own + own := []string{"Content-Type", "application/json", "Sec-Fetch-Mode", "cors", "Sec-Fetch-Dest", "empty"} + call("the page's own origin", true, "POST", save, "127.0.0.1:3430", append([]string{"Origin", "http://127.0.0.1:3430", "Sec-Fetch-Site", "same-origin"}, own...)...) + call("the page's own origin, an old browser", true, "POST", save, "127.0.0.1:3430", append([]string{"Origin", "http://127.0.0.1:3430"}, own...)...) + call("the page's own origin on the LAN", true, "POST", save, "192.168.1.20:3430", append([]string{"Origin", "http://192.168.1.20:3430", "Sec-Fetch-Site", "same-origin"}, own...)...) + call("behind a proxy that keeps the Host", true, "POST", save, "magpie.example.com", append([]string{"Origin", "https://magpie.example.com"}, own...)...) + // a proxy that passes on a Host of its own (nginx's default): the + // browser's word is enough, and so is MAGPIE_PUBLIC_URL's address + call("behind a proxy that rewrites the Host", true, "POST", save, "127.0.0.1:3430", append([]string{"Origin", "https://magpie.example.com", "Sec-Fetch-Site", "same-origin"}, own...)...) + call("a page's own read", true, "GET", "/api/state", "127.0.0.1:3430", "Sec-Fetch-Site", "same-origin", "Sec-Fetch-Mode", "cors", "Sec-Fetch-Dest", "empty") + call("the address typed in", true, "GET", "/api/state", "127.0.0.1:3430", "Sec-Fetch-Site", "none", "Sec-Fetch-Mode", "navigate", "Sec-Fetch-Dest", "document") + call("a client that isn't a browser, with the key's cookie", true, "POST", save, "127.0.0.1:3430", "Content-Type", "application/json") + // the page's files aren't the API + call("the page itself from a link elsewhere", true, "GET", "/", "127.0.0.1:3430", "Sec-Fetch-Site", "cross-site", "Sec-Fetch-Mode", "navigate", "Sec-Fetch-Dest", "document") + + t.Setenv("MAGPIE_PUBLIC_URL", "https://magpie.example.com/") + call("an old browser behind a proxy that rewrites the Host, MAGPIE_PUBLIC_URL set", true, "POST", save, "127.0.0.1:3430", append([]string{"Origin", "https://magpie.example.com"}, own...)...) + call("a sibling subdomain, MAGPIE_PUBLIC_URL set", false, "POST", save, "127.0.0.1:3430", marks("same-site", "Origin", "https://blog.example.com")...) +}