Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

plugin pages: magpie web reaches a page's local service on its own address, so the chat page works from another computer

yetone5eab14a8ccf6
diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md
index 1e488228d..250544adb 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. 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 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, 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`. 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; 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/<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, 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/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md
index 1a5e3e451..f47eafec4 100644
--- a/docs/subsystems/plugin-runtime.md
+++ b/docs/subsystems/plugin-runtime.md
@@ -270,7 +270,7 @@ still means off; a page is its own plugin's to turn on and off.
| Router strategy | A module's `export const strategies = {name: (pool, seats, options) => order}` (or `{order}` objects) are routings `<short name>/<name>`, registered with `routes.Register` while the gateway serves `middleware.Points()` and the plugin is on and loaded; off or reloaded, they are removed. 20ms each, fail open: an error, a timeout or what isn't an order of the seats is the listed order, counted on the Plugins page. The routing pickers offer the served ones (`jsRoutings` in the settings state); a routing saved whose plugin is gone shows as it is and is the listed order. providers.json keeps such a routing as saved (`provider.PluginRouting`), so a plugin turned off and on again routes its groups again. | `plugins/middleware` ("JS gateway plugins", from the same module as its [middleware](gateway-middleware.md)) | [`points.go`](../../internal/middleware/points.go), [`app.js`](../../internal/gui/assets/app.js), [`client.js`](../../internal/gui/assets/plugins/routing/client.js), [`groups_cli.go`](../../internal/cli/groups_cli.go), [`routing.go`](../../internal/provider/routing.go) |
| Usage observer | `export function onUsage(row, options)` gets each usage row of an allow-list (no bodies, prompts or ids), from a bounded queue off the request path: a full queue drops and counts, and a request never waits. 250ms each, fail open. | `plugins/middleware` ("JS gateway plugins", from the same module as its [middleware](gateway-middleware.md)) | [`points.go`](../../internal/middleware/points.go) |
| Tool | Its OpenCode `tool` hook's tools, offered to every agent by magpie's MCP server at `/mcp/magpie/tools`, each named `<plugin>_<tool>`, each call held to the calling key's limit and run in the host within 55s. Off, no tool is listed and a call says the plugin is off. | `plugins/tools` ("Plugin tools", Essential; `InUse` counts the plugins on that give tools, from `plugin-tools.json`), `gwtool.PluginTools` | [Plugin tools](plugin-tools.md) |
-| A page in the window | `magpie.page {title, file, icon}` and `magpie.permissions` in package.json, installed from npm, GitHub or a folder like any plugin (`plugin.WindowPage`: `file` an .html inside the plugin, the icon in the page's folder, reads kept to `plugin.PageReads`). An on plugin's page gets a tab in the sidebar's Plugins group, after the built-in pages (`pluginpages.js`, a kernel `page` part). It runs in an iframe sandboxed to `allow-scripts`, its files served from `/_magpie/plugin/<token>/` (an HMAC of the spec with a secret of this run) under a policy of `sandbox allow-scripts`, its own folder only, `connect-src 'none'`. The frame talks to the window by `postMessage`: the window answers only its own frame (`ev.source`), with the theme, its own options (`/api/plugin-pages/options`, at most once a second, saved without restarting the host for a page-only plugin) and the reads it declared (`/api/plugin-pages/read`, checked again by the server): `usage:summary` (totals and the top 20 models) and `providers:list` (ids and names). Nothing secret is readable, since a page can still send its frame to another site. `noFramedAPI` turns away every `/api/` request a sandboxed frame or another site can send (`Origin: null`, `Sec-Fetch-Dest` a frame, a cross-site subresource), since the desktop window's API has no key; `webGuard` lets the prefix through without the cookie the frame never sends, and the token is the key. A page that throws, or doesn't say hello in 10s, is broken through the kernel (`ctx.broke`), with Try again. The Plugins page shows the page and its reads on the row before the plugin is on. A plugin that is only a page is in-magpie-only: no Bun host starts for it. A page whose plugin also has a part for the host (a local service its page goes to, as Magiczerowxy/magpie-chat's does) starts the host when its HTML is served, if none is up (`pageHost`, `plugin.Warm`), waiting up to 7s: the host otherwise starts only on a call, so after a Restart (a plugin installed, updated or set, a Bun update) or a crash the page's service was down, and WebKit leaves a frame that navigates to a refused address on its old document with no error. Discover lists a market entry of `kind: "page"` under Pages with the Page chip, and a GitHub repository tagged `magpie-plugin` whose package.json has `magpie.page.file` as a Page (`TaggedRepos`, which then checks that file is committed, as it does a provider's entry; `TestTaggedRepos`, `plugin-kinds-discover.test.cjs`). Tests: `TestWindowPageStaysInside`, `TestPluginPageServedShutIn`, `TestPluginPageReadsWhatItDeclared`, `TestPluginPageNoAPI`, `TestPluginPageWebGuard`, `TestPluginPageStartsItsHost`, `plugin-page.test.cjs`. Example: `internal/gui/testdata/page-plugin`. | the window, no built-in plugin: the page is the plugin's own on/off | [`page.go`](../../internal/plugin/page.go), [`pluginpage.go`](../../internal/gui/pluginpage.go), [`pagebridge.js`](../../internal/gui/pagebridge.js), [`pluginpages.js`](../../internal/gui/assets/pluginpages.js) |
+| A page in the window | `magpie.page {title, file, icon}` and `magpie.permissions` in package.json, installed from npm, GitHub or a folder like any plugin (`plugin.WindowPage`: `file` an .html inside the plugin, the icon in the page's folder, reads kept to `plugin.PageReads`). An on plugin's page gets a tab in the sidebar's Plugins group, after the built-in pages (`pluginpages.js`, a kernel `page` part). It runs in an iframe sandboxed to `allow-scripts`, its files served from `/_magpie/plugin/<token>/` (an HMAC of the spec with a secret of this run) under a policy of `sandbox allow-scripts`, its own folder only, `connect-src 'none'`. The frame talks to the window by `postMessage`: the window answers only its own frame (`ev.source`), with the theme, its own options (`/api/plugin-pages/options`, at most once a second, saved without restarting the host for a page-only plugin) and the reads it declared (`/api/plugin-pages/read`, checked again by the server): `usage:summary` (totals and the top 20 models) and `providers:list` (ids and names). Nothing secret is readable, since a page can still send its frame to another site. `noFramedAPI` turns away every `/api/` request a sandboxed frame or another site can send (`Origin: null`, `Sec-Fetch-Dest` a frame, a cross-site subresource), since the desktop window's API has no key; `webGuard` lets the prefix through without the cookie the frame never sends, and the token is the key. A page that throws, or doesn't say hello in 10s, is broken through the kernel (`ctx.broke`), with Try again. The Plugins page shows the page and its reads on the row before the plugin is on. A plugin that is only a page is in-magpie-only: no Bun host starts for it. A page whose plugin also has a part for the host (a local service its page goes to, as Magiczerowxy/magpie-chat's does) starts the host when its HTML is served, if none is up (`pageHost`, `plugin.Warm`), waiting up to 7s: the host otherwise starts only on a call, so after a Restart (a plugin installed, updated or set, a Bun update) or a crash the page's service was down, and WebKit leaves a frame that navigates to a refused address on its old document with no error. A page reaches its service through magpie too, when the plugin declares it (`magpie.page.service {port, option}`, `plugin.ServiceSpec`: the port, or the plugin option named, from its plugins.json `options`): in `magpie web`, where 127.0.0.1 is the viewer's own computer, not the server (aigcfree on Discord: a server behind nginx, a Windows PC's browser, "127.0.0.1 refused to connect"), `/api/plugin-pages` gives the page a `service` under its token, `_magpie/service/`, and the bridge hands it to the frame as `magpie.service`, an absolute address (the desktop window gets none, and the page goes to 127.0.0.1 as before; a slot page gets none). `servePageService` reverse-proxies it to 127.0.0.1:<port>: Host set to the service's own (its rebinding check), the window's cookie taken off, Origin only absent or `null` (403 otherwise), Set-Cookie dropped, everything it sends sandboxed (`sandbox allow-scripts; frame-ancestors 'self'`, `Referrer-Policy: no-referrer`), streamed as it comes (`FlushInterval -1`, `X-Accel-Buffering: no` on an event stream, which `webCompressed` never gzips), a redirect to its own address made relative, and the gateway's port never served (a request from this server is loopback, which the gateway takes without a key). The way in is the page's: the token, which only a signed-in `/api` hands out, behind `AllowGuard`; the service stays on loopback. Its entry starts the host as the page's HTML does, and a service not up yet answers its frame with a 502 page that tries again in 2s. The chat page (`@magpie-community/page-chat` 0.1.1) goes to `magpie.service` when given one, else 127.0.0.1, and asks its `api/…` by relative address. Tests: `TestPluginPageServiceListedToBrowserOnly`, `TestPluginPageServiceSpec`, `TestPluginPageServiceProxied`, `TestPluginPageServiceDown`, `TestServiceLocation`, `plugin-page.test.cjs` (`magpie.service`). Discover lists a market entry of `kind: "page"` under Pages with the Page chip, and a GitHub repository tagged `magpie-plugin` whose package.json has `magpie.page.file` as a Page (`TaggedRepos`, which then checks that file is committed, as it does a provider's entry; `TestTaggedRepos`, `plugin-kinds-discover.test.cjs`). Tests: `TestWindowPageStaysInside`, `TestPluginPageServedShutIn`, `TestPluginPageReadsWhatItDeclared`, `TestPluginPageNoAPI`, `TestPluginPageWebGuard`, `TestPluginPageStartsItsHost`, `plugin-page.test.cjs`. Example: `internal/gui/testdata/page-plugin`. | the window, no built-in plugin: the page is the plugin's own on/off | [`page.go`](../../internal/plugin/page.go), [`pluginpage.go`](../../internal/gui/pluginpage.go), [`pagebridge.js`](../../internal/gui/pagebridge.js), [`pluginpages.js`](../../internal/gui/assets/pluginpages.js) |
`plugins/middleware` is now "JS gateway plugins". Apply registers the chain and `usage.Observe(middleware.Points())`; off, no JS middleware, strategy or `onUsage` runs, and a pool routed by a JS strategy is its listed order. `InUse` is unchanged. ([`middleware.go`](../../plugins/middleware/middleware.go))
diff --git a/internal/gui/api.go b/internal/gui/api.go
index 21dc67db9..e0953b006 100644
--- a/internal/gui/api.go
+++ b/internal/gui/api.go
@@ -850,7 +850,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
mux := http.NewServeMux()
mux.Handle("/", devPage(revalidated(http.FileServer(http.FS(staticFS())))))
devRoutes(mux)
- pluginPageRoutes(mux)
+ pluginPageRoutes(mux, isWeb(w))
// boot.js hands the page the saved language and theme before it paints:
// they came only with the settings, so the tabs showed English first
mux.HandleFunc("GET /boot.js", func(rw http.ResponseWriter, r *http.Request) {
diff --git a/internal/gui/assets/pluginpages.js b/internal/gui/assets/pluginpages.js
index 3b67be5e2..ae8cc7c18 100644
--- a/internal/gui/assets/pluginpages.js
+++ b/internal/gui/assets/pluginpages.js
@@ -92,8 +92,10 @@
p.hello = true;
clearTimeout(p.timer);
p.said?.();
- // a panel is told where it is: the provider whose editor it is in
- return { ...theme(), context: p.context || {} };
+ // a panel is told where it is: the provider whose editor it is in;
+ // a page served to a browser, where its local service is through
+ // this server (pageservice.go), relative to the page
+ return { ...theme(), context: p.context || {}, service: (!p.context && e.service) || "" };
case "theme":
return theme();
case "options.get":
diff --git a/internal/gui/pagebridge.js b/internal/gui/pagebridge.js
index 1316c3b2e..d4aca0fa3 100644
--- a/internal/gui/pagebridge.js
+++ b/internal/gui/pagebridge.js
@@ -13,6 +13,13 @@
// magpie.context where a panel is (P5): { provider: {
// id, name } } in a provider's editor,
// else {}; set once magpie.ready is
+// magpie.service the address of the page's local service
+// (package.json's magpie.page.service)
+// through magpie, set once magpie.ready
+// is, on a page a browser opened through
+// magpie web; "" where 127.0.0.1 is the
+// service's own computer (the app's
+// window) or magpie is older
// magpie.onAction(fn) fn({ id, provider | agent: { id, name } })
// when one of its magpie.actions is picked
// in a row's menu (P6); one picked before
@@ -94,6 +101,7 @@
const api = {
theme: null,
context: {},
+ service: "",
onTheme(fn) { themed.push(fn); },
onAction(fn) {
acting = fn;
@@ -105,9 +113,11 @@
},
read: (name, params) => call("read", { name, params }),
};
- api.ready = call("hello").then(({ context, ...theme }) => {
+ api.ready = call("hello").then(({ context, service, ...theme }) => {
api.theme = theme;
api.context = context || {};
+ api.service = "";
+ try { if (service) api.service = new URL(service, location.href).href; } catch { /* none */ }
paint(theme);
return theme;
});
diff --git a/internal/gui/pageservice.go b/internal/gui/pageservice.go
new file mode 100644
index 000000000..d4407eb7f
--- /dev/null
+++ b/internal/gui/pageservice.go
@@ -0,0 +1,180 @@
+package gui
+
+import (
+ "fmt"
+ "log"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/yetone/magpie/internal/gateway"
+)
+
+// A plugin's page can be the way into a local service its host part runs
+// (package.json's magpie.page.service, plugin.ServiceSpec): the community
+// chat page (@magpie-community/page-chat) sends its frame to the chat
+// server on 127.0.0.1. In the desktop window that is this computer. In a
+// browser on another computer, opening `magpie web` (aigcfree on Discord:
+// a server behind nginx, a Windows PC's browser), 127.0.0.1 is that
+// computer, and the frame showed "127.0.0.1 refused to connect".
+//
+// So a page served to a browser is told (/api/plugin-pages' service, the
+// bridge's magpie.service) where the same service is on this server's own
+// address: pageServicePath under the page's token. The service stays on
+// 127.0.0.1, and reaching it takes what reaching the page's files takes:
+// the token, which only a signed-in /api hands out (webGuard), and the
+// allow list before it (gateway.AllowGuard).
+
+// pageServicePath is where a page's service is, under the page's token:
+// pluginPagePrefix + token + "/" + pageServicePath + the service's path.
+const pageServicePath = "_magpie/service/"
+
+// pageServicePolicy is added to everything the service sends: whatever
+// it serves runs sandboxed, in an origin of its own, as the page's frame
+// does, even opened by itself in a tab. On this server's own origin, the
+// plugin's scripts would have the window's cookie and its /api.
+const pageServicePolicy = "sandbox allow-scripts; frame-ancestors 'self'"
+
+// pageServiceTransport dials the service on loopback, never through a
+// proxy.
+var pageServiceTransport = &http.Transport{
+ Proxy: nil,
+ DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext,
+ MaxIdleConns: 16,
+ IdleConnTimeout: 90 * time.Second,
+ ResponseHeaderTimeout: 0, // a chat's first token can be slow
+}
+
+// servicePort is the port p's service is on, or 0 when it has none that
+// can be served: the gateway's own port never is, since a request from
+// this server comes from loopback, which the gateway takes without a key.
+func (p *pluginPage) servicePort() int {
+ if p == nil || p.service == nil {
+ return 0
+ }
+ port := p.service.ServicePort(p.options)
+ if strconv.Itoa(port) == gateway.Port() {
+ return 0
+ }
+ return port
+}
+
+// servePageService passes r, a request under p's pageServicePath, to p's
+// service on 127.0.0.1, as a request from this computer: Host is the
+// service's own, which its DNS-rebinding check wants; the window's cookie
+// is taken off; Origin goes as it came, "null" from the page's sandboxed
+// frame. What comes back is sandboxed (pageServicePolicy), sets no cookie
+// on this server, sends no Referer on (the address holds the token), and
+// streams as it comes (an event stream, a WebSocket).
+func servePageService(rw http.ResponseWriter, r *http.Request, p *pluginPage, tok string) {
+ // a sandboxed page's requests carry Origin: null, and a navigation
+ // none; another site's page has no business here
+ if o, sent := r.Header["Origin"]; sent && (len(o) != 1 || o[0] != "null") {
+ http.Error(rw, "this is a plugin page's service: only its page asks it", http.StatusForbidden)
+ return
+ }
+ port := p.servicePort()
+ target := net.JoinHostPort("127.0.0.1", strconv.Itoa(port))
+ root := pluginPagePrefix + tok + "/" + pageServicePath
+ raw := strings.TrimPrefix(r.URL.EscapedPath(), root)
+ if raw == r.URL.EscapedPath() {
+ raw = strings.TrimPrefix(r.URL.Path, root)
+ }
+ upPath, err := url.PathUnescape("/" + raw)
+ if err != nil {
+ http.Error(rw, "bad path", http.StatusBadRequest)
+ return
+ }
+ // the page itself: its plugin's host, which runs the service, is up
+ // first, as for the page's HTML (pageHost)
+ if raw == "" && p.hosted {
+ pageHost(r.Context())
+ }
+ // how deep the request is under the service's root, for a redirect
+ // the service sends to one of its own paths
+ up := strings.Repeat("../", strings.Count(raw, "/"))
+ rp := &httputil.ReverseProxy{
+ Transport: pageServiceTransport,
+ Rewrite: func(pr *httputil.ProxyRequest) {
+ pr.Out.URL.Scheme = "http"
+ pr.Out.URL.Host = target
+ pr.Out.URL.Path = upPath
+ pr.Out.URL.RawPath = ""
+ if "/"+raw != upPath {
+ pr.Out.URL.RawPath = "/" + raw
+ }
+ pr.Out.URL.RawQuery = pr.In.URL.RawQuery
+ pr.Out.Host = target
+ pr.Out.Header.Del("Cookie")
+ },
+ FlushInterval: -1,
+ ModifyResponse: func(res *http.Response) error {
+ h := res.Header
+ h.Del("Set-Cookie")
+ h.Add("Content-Security-Policy", pageServicePolicy)
+ h.Set("Referrer-Policy", "no-referrer")
+ h.Set("X-Content-Type-Options", "nosniff")
+ if strings.HasPrefix(strings.ToLower(h.Get("Content-Type")), "text/event-stream") {
+ // nginx in front holds a response back until it ends
+ // unless told not to
+ h.Set("X-Accel-Buffering", "no")
+ }
+ if loc := h.Get("Location"); loc != "" {
+ h.Set("Location", serviceLocation(loc, port, up))
+ }
+ return nil
+ },
+ ErrorHandler: func(rw http.ResponseWriter, r *http.Request, err error) {
+ log.Printf("plugin page: %s's service on %s: %v", p.Name, target, err)
+ h := rw.Header()
+ h.Set("Content-Security-Policy", "sandbox allow-scripts; default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'self'")
+ h.Set("Referrer-Policy", "no-referrer")
+ h.Set("Cache-Control", "no-store")
+ if raw == "" && r.Method == http.MethodGet {
+ // the page's frame, sent here before the service is up
+ // (a host still starting): it tries again by itself; a
+ // sandboxed document refreshes only with allow-scripts
+ h.Set("Content-Type", "text/html; charset=utf-8")
+ rw.WriteHeader(http.StatusBadGateway)
+ fmt.Fprint(rw, `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="2"><style>body{font:13px/1.5 system-ui,sans-serif;display:grid;place-items:center;height:90vh;margin:0;color:GrayText}</style><p>The plugin's service isn't answering yet. Trying again…</p>`)
+ return
+ }
+ http.Error(rw, "the plugin's service isn't answering", http.StatusBadGateway)
+ },
+ }
+ rp.ServeHTTP(rw, r)
+}
+
+// serviceLocation is a redirect the service on port sent, made to go
+// through this server: one to the service's own address, or to a path
+// of its own, becomes that path under the service's root, reached from
+// a request up levels below it; one to anywhere else is left alone.
+func serviceLocation(loc string, port int, up string) string {
+ u, err := url.Parse(loc)
+ if err != nil {
+ return loc
+ }
+ if u.Scheme != "" || u.Host != "" {
+ own := u.Scheme == "http" && (u.Host == "127.0.0.1:"+strconv.Itoa(port) || u.Host == "localhost:"+strconv.Itoa(port))
+ if !own {
+ return loc
+ }
+ } else if !strings.HasPrefix(u.Path, "/") {
+ return loc // already relative to the request
+ }
+ rel := up + strings.TrimPrefix(u.EscapedPath(), "/")
+ if rel == "" {
+ rel = "./"
+ }
+ if u.RawQuery != "" {
+ rel += "?" + u.RawQuery
+ }
+ if u.Fragment != "" {
+ rel += "#" + u.EscapedFragment()
+ }
+ return rel
+}
diff --git a/internal/gui/pageservice_test.go b/internal/gui/pageservice_test.go
new file mode 100644
index 000000000..42e9e7fff
--- /dev/null
+++ b/internal/gui/pageservice_test.go
@@ -0,0 +1,377 @@
+package gui
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/plugin"
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// fakeService is a plugin's local service on 127.0.0.1, as the chat
+// page's server is: what it saw of the last request, a page, an event
+// stream that sends one event and then waits for more, and a redirect to
+// its own address.
+type fakeService struct {
+ srv *httptest.Server
+ port int
+ mu sync.Mutex
+ seen http.Header
+ host string
+ path string
+ more chan struct{}
+}
+
+func newFakeService(t *testing.T) *fakeService {
+ t.Helper()
+ f := &fakeService{more: make(chan struct{})}
+ f.srv = httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ f.seen, f.host, f.path = r.Header.Clone(), r.Host, r.URL.RequestURI()
+ f.mu.Unlock()
+ switch r.URL.Path {
+ case "/":
+ http.SetCookie(rw, &http.Cookie{Name: "svc", Value: "1"})
+ rw.Header().Set("Content-Type", "text/html; charset=utf-8")
+ fmt.Fprint(rw, `<!doctype html><title>chat</title><script src="app.js"></script>`)
+ case "/api/chat":
+ rw.Header().Set("Content-Type", "text/event-stream")
+ rw.WriteHeader(200)
+ // big enough that a compressor would hold nothing back for
+ // size, small enough to sit in its buffer
+ fmt.Fprint(rw, "data: first\n\n")
+ rw.(http.Flusher).Flush()
+ select {
+ case <-f.more:
+ case <-r.Context().Done():
+ return
+ }
+ fmt.Fprint(rw, "data: second\n\n")
+ case "/go":
+ http.Redirect(rw, r, "http://127.0.0.1:"+strconv.Itoa(f.port)+"/api/x?a=1", http.StatusFound)
+ case "/away":
+ http.Redirect(rw, r, "https://example.com/elsewhere", http.StatusFound)
+ default:
+ rw.Header().Set("Content-Type", "text/plain")
+ fmt.Fprint(rw, "path "+r.URL.Path)
+ }
+ }))
+ t.Cleanup(f.srv.Close)
+ _, p, _ := net.SplitHostPort(f.srv.Listener.Addr().String())
+ f.port, _ = strconv.Atoi(p)
+ return f
+}
+
+func (f *fakeService) last() (http.Header, string, string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.seen, f.host, f.path
+}
+
+// servicePlugins makes the sandbox of pagePlugins hold a hosted plugin
+// whose page declares service (a JSON value), with the plugin's options,
+// and answers its page as /api/plugin-pages lists it to a browser.
+func servicePlugins(t *testing.T, service string, options map[string]any) {
+ t.Helper()
+ on, _ := pagePlugins(t)
+ hosted := filepath.Join(filepath.Dir(on), "chat")
+ if err := os.CopyFS(hosted, os.DirFS("testdata/page-plugin")); err != nil {
+ t.Fatal(err)
+ }
+ pkg := `{"name": "page-chat", "main": "./index.mjs", "magpie": {"page": {"title": "Chat", "file": "page/index.html", "service": ` + service + `}}}`
+ if err := os.WriteFile(filepath.Join(hosted, "package.json"), []byte(pkg), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(hosted, "index.mjs"), []byte("export default {}\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := json.Marshal(map[string]any{"plugins": []map[string]any{{"spec": hosted, "options": options}}})
+ if err := os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), b, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ warmHost = func(context.Context) error { return nil }
+ t.Cleanup(func() { warmHost = plugin.Warm })
+}
+
+// serviceMux is the window's page routes, served to a browser (web) or
+// to the desktop window.
+func serviceMux(web bool) http.Handler {
+ mux := http.NewServeMux()
+ pluginPageRoutes(mux, web)
+ return noFramedAPI(mux)
+}
+
+func listed(t *testing.T, h http.Handler) pluginPage {
+ t.Helper()
+ var pages []pluginPage
+ w := do(h, httptest.NewRequest("GET", "/api/plugin-pages", nil))
+ if err := json.Unmarshal(w.Body.Bytes(), &pages); err != nil || len(pages) != 1 {
+ t.Fatalf("pages: %s %v", w.Body, err)
+ }
+ return pages[0]
+}
+
+// aigcfree on Discord: `magpie web` on a server, opened from a Windows
+// PC's browser, sent the chat page's frame to 127.0.0.1, the PC itself. A
+// page served to a browser is told where its service is on magpie web's
+// own address, and the desktop window is told nothing and keeps going
+// to 127.0.0.1 itself.
+func TestPluginPageServiceListedToBrowserOnly(t *testing.T) {
+ f := newFakeService(t)
+ servicePlugins(t, `{"port": `+strconv.Itoa(f.port)+`, "option": "port"}`, nil)
+ p := listed(t, serviceMux(true))
+ if p.Service != pageServicePath {
+ t.Errorf("a browser's page: service %q, want %q (relative to the page's own address)", p.Service, pageServicePath)
+ }
+ if d := listed(t, serviceMux(false)); d.Service != "" {
+ t.Errorf("the desktop window's page: service %q, want none", d.Service)
+ }
+ // the desktop window serves no service path at all
+ svc := strings.TrimSuffix(p.URL, "index.html") + pageServicePath
+ if w := do(serviceMux(false), httptest.NewRequest("GET", svc, nil)); w.Code != 404 {
+ t.Errorf("the service through the desktop window's routes: %d, want 404", w.Code)
+ }
+ if _, _, path := f.last(); path != "" {
+ t.Errorf("the service was reached from the desktop window's routes: %q", path)
+ }
+}
+
+// What a page names wrong, or a plugin that is only a page names, is no
+// service; the user's option moves it; the gateway's port never is one.
+func TestPluginPageServiceSpec(t *testing.T) {
+ f := newFakeService(t)
+ for _, c := range []struct {
+ name, service string
+ options map[string]any
+ want int
+ }{
+ {"the port named", `{"port": ` + strconv.Itoa(f.port) + `}`, nil, f.port},
+ {"a string port", `{"port": "` + strconv.Itoa(f.port) + `"}`, nil, f.port},
+ {"the option set", `{"port": 1, "option": "port"}`, map[string]any{"port": float64(f.port)}, f.port},
+ {"the option set as text", `{"port": 1, "option": "port"}`, map[string]any{"port": strconv.Itoa(f.port)}, f.port},
+ {"the option set wrong", `{"port": ` + strconv.Itoa(f.port) + `, "option": "port"}`, map[string]any{"port": "x"}, f.port},
+ {"no port", `{"option": "port"}`, nil, 0},
+ {"port out of range", `{"port": 70000}`, nil, 0},
+ {"a fraction", `{"port": 3477.5}`, nil, 0},
+ {"not an object", `"3477"`, nil, 0},
+ {"the gateway's port", `{"port": 3425}`, nil, 0},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ servicePlugins(t, c.service, c.options)
+ t.Setenv("MAGPIE_ADDR", "127.0.0.1:3425")
+ ps := pluginPages()
+ if len(ps) != 1 {
+ t.Fatalf("a wrong service lost the page: %+v", ps)
+ }
+ if got := ps[0].servicePort(); got != c.want {
+ t.Errorf("service port %d, want %d", got, c.want)
+ }
+ })
+ }
+ // a page-only plugin's page gets no service, whatever it names
+ pagePlugins(t)
+ on := filepath.Join(os.Getenv("HOME"), "src", "glance")
+ pkg := `{"name": "glance", "magpie": {"page": {"title": "G", "file": "page/index.html", "service": {"port": ` + strconv.Itoa(f.port) + `}}}}`
+ if err := os.WriteFile(filepath.Join(on, "package.json"), []byte(pkg), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ ps := pluginPages()
+ if len(ps) != 1 || ps[0].servicePort() != 0 {
+ t.Errorf("a page-only plugin's service: %+v", ps)
+ }
+ p := listed(t, serviceMux(true))
+ if p.Service != "" {
+ t.Errorf("a page-only plugin's page listed a service: %q", p.Service)
+ }
+ svc := strings.TrimSuffix(p.URL, "index.html") + pageServicePath
+ if w := do(serviceMux(true), httptest.NewRequest("GET", svc, nil)); w.Code != 404 {
+ t.Errorf("a page-only plugin's service path: %d, want 404", w.Code)
+ }
+}
+
+// The service through `magpie web`'s whole chain, with no cookie (a
+// sandboxed frame sends none): the page's token lets it in, a made-up one
+// doesn't; the service sees its own Host and no cookie; what comes back
+// is sandboxed, sets no cookie here, and an event stream arrives as it is
+// sent, not when it ends.
+func TestPluginPageServiceProxied(t *testing.T) {
+ f := newFakeService(t)
+ servicePlugins(t, `{"port": `+strconv.Itoa(f.port)+`}`, nil)
+ t.Setenv("MAGPIE_ADDR", "127.0.0.1:3425")
+ page := serviceMux(true)
+ p := listed(t, page)
+ srv := httptest.NewServer(webHandler("3430", onePortWebKey, 0, page))
+ t.Cleanup(srv.Close)
+ base := srv.URL + strings.TrimSuffix(p.URL, "index.html") + pageServicePath
+ get := func(target string, hdr ...string) *http.Response {
+ t.Helper()
+ req, _ := http.NewRequest("GET", target, nil)
+ req.Header.Set("Accept-Encoding", "gzip")
+ for i := 0; i+1 < len(hdr); i += 2 {
+ req.Header.Set(hdr[i], hdr[i+1])
+ }
+ res, err := (&http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}).Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { res.Body.Close() })
+ return res
+ }
+
+ res := get(base, "Cookie", "magpie_web_3430=the-window", "Origin", "null")
+ body, _ := io.ReadAll(res.Body)
+ if res.StatusCode != 200 || !strings.Contains(string(body), "<title>chat</title>") {
+ t.Fatalf("the service's page: %d %s", res.StatusCode, body)
+ }
+ seen, host, path := f.last()
+ if want := "127.0.0.1:" + strconv.Itoa(f.port); host != want {
+ t.Errorf("the service saw Host %q, want its own %q", host, want)
+ }
+ if path != "/" {
+ t.Errorf("the service saw path %q, want /", path)
+ }
+ if seen.Get("Cookie") != "" {
+ t.Errorf("the window's cookie reached the service: %q", seen.Get("Cookie"))
+ }
+ if res.Header.Get("Set-Cookie") != "" {
+ t.Errorf("the service set a cookie on magpie web's address: %q", res.Header.Get("Set-Cookie"))
+ }
+ if csp := strings.Join(res.Header.Values("Content-Security-Policy"), ", "); !strings.Contains(csp, "sandbox allow-scripts") || strings.Contains(csp, "allow-same-origin") {
+ t.Errorf("the service's page isn't sandboxed: %q", csp)
+ }
+ if res.Header.Get("Referrer-Policy") != "no-referrer" {
+ t.Errorf("Referrer-Policy %q", res.Header.Get("Referrer-Policy"))
+ }
+
+ // a path and query of the service's own
+ res = get(base + "api/icon/a%2Fb.png?size=2")
+ if _, _, path := f.last(); path != "/api/icon/a%2Fb.png?size=2" {
+ t.Errorf("the service saw %q", path)
+ }
+
+ // another site's page, or a made-up token, gets nowhere
+ if res = get(base, "Origin", "https://evil.example"); res.StatusCode != http.StatusForbidden {
+ t.Errorf("another site's Origin: %d, want 403", res.StatusCode)
+ }
+ if res = get(srv.URL + pluginPagePrefix + strings.Repeat("a", 32) + "/" + pageServicePath); res.StatusCode != 404 {
+ t.Errorf("a made-up token: %d, want 404", res.StatusCode)
+ }
+
+ // redirects to the service's own address stay on magpie web's
+ res = get(base + "go")
+ if loc := res.Header.Get("Location"); loc != "api/x?a=1" {
+ t.Errorf("a redirect to the service's own address: Location %q, want api/x?a=1", loc)
+ }
+ res = get(base + "away")
+ if loc := res.Header.Get("Location"); loc != "https://example.com/elsewhere" {
+ t.Errorf("a redirect elsewhere: Location %q", loc)
+ }
+
+ // the event stream: the first event arrives while the service still
+ // holds the response open
+ req, _ := http.NewRequest("POST", base+"api/chat", strings.NewReader(`{}`))
+ req.Header.Set("Accept-Encoding", "gzip")
+ req.Header.Set("Origin", "null")
+ sres, err := http.DefaultTransport.RoundTrip(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer sres.Body.Close()
+ if sres.Header.Get("Content-Encoding") != "" {
+ t.Errorf("the event stream was compressed: %q", sres.Header.Get("Content-Encoding"))
+ }
+ if sres.Header.Get("X-Accel-Buffering") != "no" {
+ t.Errorf("X-Accel-Buffering %q, want no (nginx would hold the stream)", sres.Header.Get("X-Accel-Buffering"))
+ }
+ lines := make(chan string, 8)
+ go func() {
+ sc := bufio.NewScanner(sres.Body)
+ for sc.Scan() {
+ lines <- sc.Text()
+ }
+ close(lines)
+ }()
+ select {
+ case l := <-lines:
+ if l != "data: first" {
+ t.Errorf("first line %q", l)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("the first event didn't arrive while the stream was open")
+ }
+ close(f.more)
+ got := ""
+ for l := range lines {
+ got += l + "\n"
+ }
+ if !strings.Contains(got, "data: second") {
+ t.Errorf("the rest of the stream: %q", got)
+ }
+}
+
+// A service that isn't up yet (the plugin's host still starting) gets
+// the page's frame a page that tries again, and a call an error.
+func TestPluginPageServiceDown(t *testing.T) {
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // held, not freed (a freed port can be handed to anything next): it
+ // hangs up on every connection, as a service not serving yet would
+ t.Cleanup(func() { l.Close() })
+ go func() {
+ for {
+ c, err := l.Accept()
+ if err != nil {
+ return
+ }
+ c.Close()
+ }
+ }()
+ _, ps, _ := net.SplitHostPort(l.Addr().String())
+ servicePlugins(t, `{"port": `+ps+`}`, nil)
+ t.Setenv("MAGPIE_ADDR", "127.0.0.1:3425")
+ page := serviceMux(true)
+ p := listed(t, page)
+ base := strings.TrimSuffix(p.URL, "index.html") + pageServicePath
+ w := do(page, httptest.NewRequest("GET", base, nil))
+ if w.Code != http.StatusBadGateway || !strings.Contains(w.Body.String(), `http-equiv="refresh"`) {
+ t.Errorf("the frame before the service is up: %d %s", w.Code, w.Body)
+ }
+ if csp := w.Header().Get("Content-Security-Policy"); !strings.Contains(csp, "sandbox allow-scripts") {
+ t.Errorf("the retry page's CSP %q", csp)
+ }
+ w = do(page, httptest.NewRequest("POST", base+"api/chat", strings.NewReader("{}")))
+ if w.Code != http.StatusBadGateway || strings.Contains(w.Body.String(), "refresh") {
+ t.Errorf("a call before the service is up: %d %s", w.Code, w.Body)
+ }
+}
+
+func TestServiceLocation(t *testing.T) {
+ for _, c := range []struct{ loc, up, want string }{
+ {"http://127.0.0.1:3477/", "", "./"},
+ {"http://localhost:3477/a/b?x=1#f", "../", "../a/b?x=1#f"},
+ {"/api/x", "../../", "../../api/x"},
+ {"api/x", "../", "api/x"},
+ {"http://127.0.0.1:3478/", "", "http://127.0.0.1:3478/"},
+ {"https://127.0.0.1:3477/", "", "https://127.0.0.1:3477/"},
+ {"https://example.com/", "", "https://example.com/"},
+ } {
+ if got := serviceLocation(c.loc, 3477, c.up); got != c.want {
+ t.Errorf("serviceLocation(%q, %q) = %q, want %q", c.loc, c.up, got, c.want)
+ }
+ }
+}
diff --git a/internal/gui/pluginpage.go b/internal/gui/pluginpage.go
index 1952c8298..f6a4df8ea 100644
--- a/internal/gui/pluginpage.go
+++ b/internal/gui/pluginpage.go
@@ -81,10 +81,16 @@ type pluginPage struct {
// Actions are its items in magpie's menus (plugin.ActionSpec); each
// opens this page
Actions []pluginAction `json:"actions,omitempty"`
+ // Service is where a browser reaches the page's local service
+ // (plugin.ServiceSpec) through this server, relative to the page's own
+ // address: only on a page served to a browser (servePageService)
+ Service string `json:"service,omitempty"`
token string
dir string
file string // its HTML, relative to dir, with forward slashes
hosted bool // its plugin has a part for the host too (pageHost)
+ service *plugin.ServiceSpec
+ options map[string]any // its plugin's, as plugins.json keeps them
}
// pluginAction is an item a plugin's page adds to one of magpie's menus.
@@ -149,7 +155,10 @@ func windowParts() (pages []pluginPage, panels []pluginPanel) {
tok := pageToken(e.Spec)
rel, _ := filepath.Rel(spec.Dir, spec.File)
p := pluginPage{Spec: e.Spec, Name: name, Key: key, Title: spec.Title, Titles: spec.Titles, Reads: reads, token: tok, dir: spec.Dir,
- URL: pluginPagePrefix + tok + "/" + filepath.ToSlash(rel), file: filepath.ToSlash(rel), hosted: !only}
+ URL: pluginPagePrefix + tok + "/" + filepath.ToSlash(rel), file: filepath.ToSlash(rel), hosted: !only, options: e.Options}
+ if !only {
+ p.service = spec.Service
+ }
if p.Title == "" {
p.Title = plugin.ShortName(name)
}
@@ -280,12 +289,9 @@ func pageHost(ctx context.Context) {
}
}
-// servePluginPage serves a file of a plugin's page, by its token.
-func servePluginPage(rw http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet && r.Method != http.MethodHead {
- http.Error(rw, "method not allowed", http.StatusMethodNotAllowed)
- return
- }
+// servePluginPage serves a file of a plugin's page, by its token, and on
+// a page served to a browser (web) the page's local service too.
+func servePluginPage(rw http.ResponseWriter, r *http.Request, web bool) {
rest := strings.TrimPrefix(r.URL.Path, pluginPagePrefix)
tok, rel, ok := strings.Cut(rest, "/")
if !ok || len(tok) != 32 {
@@ -294,11 +300,26 @@ func servePluginPage(rw http.ResponseWriter, r *http.Request) {
}
// the page's or the panel's folder, by its token
dir, entry, hosted := "", "", false
+ var page *pluginPage
pages, panels := windowParts()
- for _, p := range pages {
+ for i, p := range pages {
if hmac.Equal([]byte(p.token), []byte(tok)) {
dir, entry, hosted = p.dir, p.file, p.hosted
+ page = &pages[i]
+ }
+ }
+ // the service's paths are never a file of the page's
+ if strings.HasPrefix(rel, pageServicePath) {
+ if !web || page == nil || page.servicePort() == 0 {
+ http.NotFound(rw, r)
+ return
}
+ servePageService(rw, r, page, tok)
+ return
+ }
+ if r.Method != http.MethodGet && r.Method != http.MethodHead {
+ http.Error(rw, "method not allowed", http.StatusMethodNotAllowed)
+ return
}
for _, p := range panels {
if hmac.Equal([]byte(p.token), []byte(tok)) {
@@ -367,13 +388,22 @@ func apiFramed(r *http.Request) bool {
return r.Header.Get("Sec-Fetch-Site") == "cross-site" && r.Header.Get("Sec-Fetch-Dest") != "document"
}
-func pluginPageRoutes(mux *http.ServeMux) {
- mux.HandleFunc(pluginPagePrefix, servePluginPage)
+// pluginPageRoutes are the routes of the plugins' pages and panels. web is
+// whether the window is a browser's (isWeb): only there is a page's local
+// service served through this server (servePageService), since only there
+// can 127.0.0.1 be another computer than this one.
+func pluginPageRoutes(mux *http.ServeMux, web bool) {
+ mux.HandleFunc(pluginPagePrefix, func(rw http.ResponseWriter, r *http.Request) { servePluginPage(rw, r, web) })
mux.HandleFunc("GET /api/plugin-pages", func(rw http.ResponseWriter, r *http.Request) {
out := pluginPages()
if out == nil {
out = []pluginPage{}
}
+ for i := range out {
+ if web && out[i].servicePort() > 0 {
+ out[i].Service = strings.Repeat("../", strings.Count(out[i].file, "/")) + pageServicePath
+ }
+ }
writeJSON(rw, out)
})
mux.HandleFunc("GET /api/plugin-panels", func(rw http.ResponseWriter, r *http.Request) {
diff --git a/internal/gui/pluginpage_test.go b/internal/gui/pluginpage_test.go
index 4e6394c11..c1941cf89 100644
--- a/internal/gui/pluginpage_test.go
+++ b/internal/gui/pluginpage_test.go
@@ -72,7 +72,7 @@ func pagePlugins(t *testing.T) (on, off string) {
func pageMux() http.Handler {
mux := http.NewServeMux()
- pluginPageRoutes(mux)
+ pluginPageRoutes(mux, false)
mux.HandleFunc("GET /api/state", func(rw http.ResponseWriter, r *http.Request) {
writeJSON(rw, map[string]string{"secret": "the window's"})
})
@@ -139,7 +139,7 @@ func TestPluginPageServedShutIn(t *testing.T) {
r := httptest.NewRequest("GET", "/", nil)
r.URL.Path = path
w := httptest.NewRecorder()
- servePluginPage(w, r)
+ servePluginPage(w, r, false)
if w.Code == 200 || strings.Contains(w.Body.String(), "SECRET") || strings.Contains(w.Body.String(), `"name"`) {
t.Errorf("%s: %d %s", path, w.Code, w.Body)
}
diff --git a/internal/gui/pluginpanel_test.go b/internal/gui/pluginpanel_test.go
index c3bf4d6c9..b5a9209c1 100644
--- a/internal/gui/pluginpanel_test.go
+++ b/internal/gui/pluginpanel_test.go
@@ -117,7 +117,7 @@ func TestPluginPanelsServedShutIn(t *testing.T) {
r := httptest.NewRequest("GET", "/", nil)
r.URL.Path = path
w := httptest.NewRecorder()
- servePluginPage(w, r)
+ servePluginPage(w, r, false)
if w.Code == 200 || strings.Contains(w.Body.String(), "SECRET") || strings.Contains(w.Body.String(), `"name"`) {
t.Errorf("%s: %d %s", path, w.Code, w.Body)
}
@@ -127,7 +127,7 @@ func TestPluginPanelsServedShutIn(t *testing.T) {
r := httptest.NewRequest("GET", "/", nil)
r.URL.Path = pluginPagePrefix + pageToken(off+"\x00panel\x000") + "/notes.html"
w = httptest.NewRecorder()
- servePluginPage(w, r)
+ servePluginPage(w, r, false)
if w.Code == 200 {
t.Errorf("a plugin switched off's panel: %d", w.Code)
}
diff --git a/internal/gui/tests/plugin-page.test.cjs b/internal/gui/tests/plugin-page.test.cjs
index 376b8b3a5..d43d83c40 100644
--- a/internal/gui/tests/plugin-page.test.cjs
+++ b/internal/gui/tests/plugin-page.test.cjs
@@ -31,7 +31,9 @@ const entry = (tok, name, title, reads, file = "index.html") => ({
const TITLES = { zh: "用量速览", "zh-TW": "用量速覽", ja: "使用量の概要" };
const pages = [
{ ...entry(GLANCE, "glance", "Usage glance", ["usage:summary"]), titles: TITLES },
- entry(PROBE, "probe", "Probe", []),
+ // a page with a local service (magpie.page.service), as /api/plugin-pages
+ // lists it to a browser: relative to the page's address
+ { ...entry(PROBE, "probe", "Probe", []), service: "_magpie/service/" },
entry(OPEN, "open", "Probe without a policy", []),
entry(BROKEN, "broken", "Broken", []),
];
@@ -54,6 +56,7 @@ const PROBE_HTML = `<!doctype html><meta charset="utf-8"><script src="_magpie/br
const PROBE_JS = `(async () => {
const out = {};
await magpie.ready;
+ out.service = magpie.service;
try { const r = await fetch("/api/state?probe=1"); out.fetch = "status " + r.status; } catch (e) { out.fetch = "refused"; }
try { out.storage = typeof localStorage.length; } catch (e) { out.storage = "refused"; }
try { out.cookie = document.cookie; } catch (e) { out.cookie = "refused"; }
@@ -201,6 +204,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(probe.read2, "Probe doesn't ask to read providers:list", where);
assert.equal(seen.api.length, 0, `${where}: nothing reached /api`);
assert.equal(seen.reads.length, 1, `${where}: an undeclared read never reached the server`);
+ // its service, where the window's server serves it: an absolute
+ // address under the page's own
+ assert.match(probe.service, new RegExp(`^https?://[^/]+/_magpie/plugin/${PROBE}/_magpie/service/$`), `${where}: magpie.service`);
// a page with no stylesheet of its own reads as part of the window
const win = await page.evaluate(() => {
const d = document.createElement("div");
@@ -226,6 +232,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(open.fetch.startsWith("status") || open.fetch === "refused", true, where);
assert.equal(seen.api.length, 1, `${where}: the fetch went out`);
assert.equal(seen.api[0].origin, "null", `${where}: as Origin: null`);
+ assert.equal(open.service, "", `${where}: a page with no service has no magpie.service`);
assert.ok(!seen.api[0].cookie, `${where}: without a cookie`);
// a message from another frame naming a page is nothing
diff --git a/internal/gui/web.go b/internal/gui/web.go
index 9be29b8a8..25081367f 100644
--- a/internal/gui/web.go
+++ b/internal/gui/web.go
@@ -383,12 +383,17 @@ func webCompressed(next http.Handler) http.Handler {
// gzipETag ends the ETag of a gzipped response.
const gzipETag = "-gzip"
-// compressible: text, scripts, JSON and SVG; not PNG, WebP, ICO or JPEG.
+// compressible: text, scripts, JSON and SVG; not PNG, WebP, ICO or JPEG,
+// and not an event stream, which gzip holds back until a block fills (a
+// plugin page's service streams a chat's tokens, servePageService).
func compressible(ct string) bool {
ct = strings.ToLower(strings.TrimSpace(ct))
if i := strings.IndexByte(ct, ';'); i >= 0 {
ct = strings.TrimSpace(ct[:i])
}
+ if ct == "text/event-stream" {
+ return false
+ }
return strings.HasPrefix(ct, "text/") || strings.HasSuffix(ct, "javascript") ||
strings.HasSuffix(ct, "json") || ct == "image/svg+xml"
}
diff --git a/internal/plugin/page.go b/internal/plugin/page.go
index 786e086de..e7d70e634 100644
--- a/internal/plugin/page.go
+++ b/internal/plugin/page.go
@@ -7,6 +7,7 @@ import (
"path/filepath"
"regexp"
"slices"
+ "strconv"
"strings"
)
@@ -38,6 +39,19 @@ type PageSpec struct {
// Replaces is the built-in page (one of Replaceable) whose place in
// the sidebar the page takes while its plugin is on, or "".
Replaces string
+ // Service is the local HTTP service the plugin's host part runs for
+ // the page (magpie.page.service), or nil: magpie web serves it under
+ // its own address to a browser on another computer, where the
+ // service's 127.0.0.1 is that computer's own.
+ Service *ServiceSpec
+}
+
+// ServiceSpec is a page's local service: an HTTP server on 127.0.0.1 at
+// Port, or at the port in the plugin's option named Option when the user
+// set one (magpie.page.service {"port": 3477, "option": "port"}).
+type ServiceSpec struct {
+ Port int
+ Option string // "" when no option moves it
}
// PanelSpec is a panel a plugin adds to one of magpie's own pages: a
@@ -115,7 +129,7 @@ const maxPanels = 8
// Window is what a plugin at target adds to magpie's window, or nil when
// it adds nothing: package.json's magpie.page {title, file, icon,
-// replaces}, magpie.panels [{slot, file, title}] and magpie.actions [{id,
+// replaces, service}, magpie.panels [{slot, file, title}] and magpie.actions [{id,
// menu, title}]. A file outside the
// plugin's folder, or not .html, is no page or panel; a panel in a slot
// magpie doesn't have is left out, and so is a replaces of a page that
@@ -139,6 +153,7 @@ func Window(target string) (w *WindowSpec, only bool) {
Replaces string `json:"replaces"`
ID string `json:"id"`
Menu string `json:"menu"`
+ Service json.RawMessage `json:"service"`
}
var pkg struct {
Main string `json:"main"`
@@ -166,6 +181,12 @@ func Window(target string) (w *WindowSpec, only bool) {
if r := strings.TrimSpace(pg.Replaces); slices.Contains(Replaceable, r) {
p.Replaces = r
}
+ // a service is run by the plugin's host part: a plugin that is
+ // only a page has none, so its sandboxed page can't be handed
+ // a way to some other program's port on this computer
+ if pkg.Main != "" || len(pkg.Exports) > 0 {
+ p.Service = service(pg.Service)
+ }
w.Page = p
}
}
@@ -203,6 +224,65 @@ func Window(target string) (w *WindowSpec, only bool) {
return w, pkg.Main == "" && len(pkg.Exports) == 0
}
+// service is a page's magpie.page.service, or nil when it names none or
+// names it wrong: {"port": a TCP port, "option": the plugin's option that
+// moves it, optional}. One that is wrong leaves the page as it is.
+func service(raw json.RawMessage) *ServiceSpec {
+ var sv struct {
+ Port any `json:"port"`
+ Option any `json:"option"`
+ }
+ if len(raw) == 0 || json.Unmarshal(raw, &sv) != nil {
+ return nil
+ }
+ port, ok := portOf(sv.Port)
+ if !ok {
+ return nil
+ }
+ out := &ServiceSpec{Port: port}
+ if o, _ := sv.Option.(string); len(strings.TrimSpace(o)) <= 64 {
+ out.Option = strings.TrimSpace(o)
+ }
+ return out
+}
+
+// portOf is v as a TCP port: a whole number from 1 to 65535, or a string
+// of one.
+func portOf(v any) (int, bool) {
+ var n float64
+ switch x := v.(type) {
+ case float64:
+ n = x
+ case string:
+ i, err := strconv.Atoi(strings.TrimSpace(x))
+ if err != nil {
+ return 0, false
+ }
+ n = float64(i)
+ default:
+ return 0, false
+ }
+ if n != float64(int(n)) || n < 1 || n > 65535 {
+ return 0, false
+ }
+ return int(n), true
+}
+
+// ServicePort is the port spec's service listens on for the plugin with
+// options: the option's value when the user set one, else the port the
+// package names.
+func (s *ServiceSpec) ServicePort(options map[string]any) int {
+ if s == nil {
+ return 0
+ }
+ if s.Option != "" {
+ if p, ok := portOf(options[s.Option]); ok {
+ return p
+ }
+ }
+ return s.Port
+}
+
// htmlInside is rel joined to dir, if that stays inside dir and is an
// .html file.
func htmlInside(dir, rel string) (string, bool) {