Skip to content

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

plugin pages: magpie web forwards a page's local service under the page's address

yetone181fd0a68271
diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md
index 1a5e3e451..d8491a9ab 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 that names that service (`magpie.page.service {port | portOption}`: a port, or the plugin option that holds one, defaulting to its `magpie.options` value) has it forwarded under its own address, `/_magpie/plugin/<token>/_service/`, to 127.0.0.1 on that port (`servePageService`), and the bridge tells the page so (`magpie.service`): opened from another computer through magpie web, the page's 127.0.0.1 was that computer's and refused (Discord DM: AIGCFREE). The token is the key, as for the page's files; the service gets its own Host (and Origin, when magpie's own), none of magpie's cookies or Authorization, and its answers keep a sandbox CSP, no referrer and no Set-Cookie; a redirect stays under the page's address. 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`, `TestPluginPageForwardsItsService`, `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/pluginpage.go b/internal/gui/pluginpage.go
index 1952c8298..b7a5eb7c3 100644
--- a/internal/gui/pluginpage.go
+++ b/internal/gui/pluginpage.go
@@ -12,6 +12,8 @@ import (
"fmt"
"log"
"net/http"
+ "net/http/httputil"
+ "net/url"
"os"
"path/filepath"
"slices"
@@ -85,6 +87,7 @@ type pluginPage struct {
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 int // the port of its local service (servePageService), or 0
}
// pluginAction is an item a plugin's page adds to one of magpie's menus.
@@ -149,7 +152,8 @@ 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,
+ service: spec.Service.ServicePort(e.Options)}
if p.Title == "" {
p.Title = plugin.ShortName(name)
}
@@ -282,10 +286,6 @@ 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
- }
rest := strings.TrimPrefix(r.URL.Path, pluginPagePrefix)
tok, rel, ok := strings.Cut(rest, "/")
if !ok || len(tok) != 32 {
@@ -293,13 +293,25 @@ func servePluginPage(rw http.ResponseWriter, r *http.Request) {
return
}
// the page's or the panel's folder, by its token
- dir, entry, hosted := "", "", false
+ dir, entry, hosted, service := "", "", false, 0
pages, panels := windowParts()
for _, p := range pages {
if hmac.Equal([]byte(p.token), []byte(tok)) {
- dir, entry, hosted = p.dir, p.file, p.hosted
+ dir, entry, hosted, service = p.dir, p.file, p.hosted, p.service
}
}
+ if service > 0 && (rel == pageServiceDir || strings.HasPrefix(rel, pageServiceDir+"/")) {
+ // its first page: the host part that runs the service is up first
+ if rel == pageServiceDir+"/" && r.Method == http.MethodGet {
+ pageHost(r.Context())
+ }
+ servePageService(rw, r, tok, service, strings.TrimPrefix(rel, pageServiceDir))
+ 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)) {
dir, entry, hosted = p.dir, p.file, p.hosted
@@ -324,7 +336,13 @@ func servePluginPage(rw http.ResponseWriter, r *http.Request) {
h.Set("Cache-Control", "no-cache")
if rel == pluginBridgePath {
h.Set("Content-Type", "text/javascript; charset=utf-8")
- http.ServeContent(rw, r, "bridge.js", time.Time{}, strings.NewReader(string(pageBridgeJS)))
+ js := string(pageBridgeJS)
+ if service > 0 {
+ // where the page's service is reached from a browser on
+ // another machine (servePageService)
+ js += "\nwindow.magpie.service = " + strconv.Quote(pluginPagePrefix+tok+"/"+pageServiceDir+"/") + ";\n"
+ }
+ http.ServeContent(rw, r, "bridge.js", time.Time{}, strings.NewReader(js))
return
}
file, ok := plugin.FileIn(dir, rel)
@@ -348,6 +366,64 @@ func servePluginPage(rw http.ResponseWriter, r *http.Request) {
http.ServeContent(rw, r, filepath.Base(file), st.ModTime(), f)
}
+// pageServiceDir is where, under a page's own address, magpie forwards to
+// the local service its plugin's host part runs (magpie.page.service).
+const pageServiceDir = "_service"
+
+// servePageService forwards a request to a page's local service on
+// 127.0.0.1. A page such as Magiczerowxy/magpie-chat's sends its frame to
+// the service it starts on 127.0.0.1, which works only in a browser on the
+// machine magpie runs on: opened from another computer through magpie
+// web, 127.0.0.1 was that computer and refused (Discord DM: AIGCFREE,
+// magpie web behind nginx). Here it is at the page's own address, with
+// the page's token as the key, as for its files (webGuard); the service
+// sees itself asked for (Host, and Origin when it is magpie's own), and
+// none of magpie's cookies or credentials. What it answers stays shut in
+// as the page is: a sandbox of its own origin, no referrer, no cookies.
+func servePageService(rw http.ResponseWriter, r *http.Request, tok string, port int, rel string) {
+ own := "127.0.0.1:" + strconv.Itoa(port)
+ base := pluginPagePrefix + tok + "/" + pageServiceDir
+ if rel == "" {
+ http.Redirect(rw, r, base+"/", http.StatusFound)
+ return
+ }
+ proxy := &httputil.ReverseProxy{
+ Rewrite: func(pr *httputil.ProxyRequest) {
+ out := pr.Out
+ out.URL.Scheme, out.URL.Host = "http", own
+ out.URL.Path, out.URL.RawPath = rel, ""
+ out.Host = own
+ out.Header.Del("Cookie")
+ out.Header.Del("Authorization")
+ if o := out.Header.Get("Origin"); o != "" && o != "null" {
+ if u, err := url.Parse(o); err == nil && u.Host == r.Host {
+ out.Header.Set("Origin", "http://"+own)
+ }
+ }
+ },
+ FlushInterval: -1, // a chat streams
+ ModifyResponse: func(res *http.Response) error {
+ h := res.Header
+ h.Del("Set-Cookie")
+ h.Add("Content-Security-Policy", "sandbox allow-scripts allow-forms allow-popups allow-modals allow-downloads")
+ h.Set("Referrer-Policy", "no-referrer")
+ h.Set("X-Content-Type-Options", "nosniff")
+ // a redirect within the service stays under the page's address
+ if loc := h.Get("Location"); strings.HasPrefix(loc, "/") && !strings.HasPrefix(loc, "//") {
+ h.Set("Location", base+loc)
+ } else if u, err := url.Parse(loc); err == nil && loc != "" && u.Host == own {
+ h.Set("Location", base+u.RequestURI())
+ }
+ return nil
+ },
+ ErrorHandler: func(rw http.ResponseWriter, r *http.Request, err error) {
+ log.Printf("plugin page: its service on %s: %v", own, err)
+ http.Error(rw, "this page's service on "+own+" is not answering: is its plugin on and its host up?", http.StatusBadGateway)
+ },
+ }
+ proxy.ServeHTTP(rw, r)
+}
+
// apiFramed is whether r is a request for /api that no page of the window's
// own makes: one from a sandboxed frame (Origin: null, which a plugin's
// page's fetch would send were its policy not to stop it), one that loads
diff --git a/internal/gui/pluginpage_test.go b/internal/gui/pluginpage_test.go
index 4e6394c11..a07ef6d72 100644
--- a/internal/gui/pluginpage_test.go
+++ b/internal/gui/pluginpage_test.go
@@ -3,10 +3,13 @@ package gui
import (
"context"
"encoding/json"
+ "io"
+ "net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
+ "strconv"
"strings"
"sync"
"testing"
@@ -373,3 +376,117 @@ func TestPluginPageActions(t *testing.T) {
t.Errorf("an action with no title: %+v, want the page's", a[1])
}
}
+
+// A page's local service (magpie.page.service) is forwarded under the
+// page's own address, so a browser on another machine reaches it through
+// magpie web: opened from another computer, the chat page's 127.0.0.1 was
+// that computer's and refused (Discord DM: AIGCFREE). The service sees
+// itself asked for and none of magpie's cookies; its answer stays
+// sandboxed, with no referrer and no cookie of its own; a redirect stays
+// under the page; the port is the user's option; a page with no service,
+// or a token that isn't a page's, forwards nothing.
+func TestPluginPageForwardsItsService(t *testing.T) {
+ on, _ := pagePlugins(t)
+ type seen struct{ host, cookie, auth, origin, path, query, body string }
+ got := make(chan seen, 8)
+ svc := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ got <- seen{r.Host, r.Header.Get("Cookie"), r.Header.Get("Authorization"), r.Header.Get("Origin"), r.URL.Path, r.URL.RawQuery, string(b)}
+ switch r.URL.Path {
+ case "/old":
+ http.Redirect(rw, r, "/new", http.StatusFound)
+ return
+ case "/away":
+ http.Redirect(rw, r, "http://"+r.Host+"/there?a=1", http.StatusFound)
+ return
+ }
+ rw.Header().Set("Set-Cookie", "s=1")
+ rw.Write([]byte("service " + r.Method))
+ }))
+ defer svc.Close()
+ port := svc.Listener.Addr().(*net.TCPAddr).Port
+
+ 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": {"options": {"port": 1}, "page": {"title": "Chat", "file": "page/index.html", "service": {"portOption": "port"}}}}`
+ 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": on}, {"spec": hosted, "options": map[string]any{"port": port}}}})
+ 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 })
+
+ pages := pluginPages()
+ if len(pages) != 2 {
+ t.Fatalf("pages: %+v", pages)
+ }
+ glance, chat := pages[0], pages[1]
+ tokOf := func(p pluginPage) string { return strings.Split(strings.TrimPrefix(p.URL, pluginPagePrefix), "/")[0] }
+ base := pluginPagePrefix + tokOf(chat) + "/" + pageServiceDir + "/"
+ h := pageMux()
+
+ // the bridge tells the page where its service is; a page with none hears nothing
+ if w := do(h, httptest.NewRequest("GET", pluginPagePrefix+tokOf(chat)+"/"+pluginBridgePath, nil)); !strings.Contains(w.Body.String(), `window.magpie.service = "`+base+`"`) {
+ t.Fatalf("the bridge doesn't name the service: %s", w.Body.String()[max(0, w.Body.Len()-200):])
+ }
+ if w := do(h, httptest.NewRequest("GET", pluginPagePrefix+tokOf(glance)+"/"+pluginBridgePath, nil)); strings.Contains(w.Body.String(), "magpie.service") {
+ t.Fatal("a page without a service is told of one")
+ }
+
+ r := httptest.NewRequest("POST", "http://magpie.example:3430"+base+"api/chat?x=1", strings.NewReader(`{"q":1}`))
+ r.Header.Set("Cookie", "magpie_web=secret")
+ r.Header.Set("Authorization", "Bearer secret")
+ r.Header.Set("Origin", "http://magpie.example:3430")
+ w := do(h, r)
+ s := <-got
+ if w.Code != 200 || w.Body.String() != "service POST" {
+ t.Fatalf("forwarded: %d %s", w.Code, w.Body)
+ }
+ own := "127.0.0.1:" + strconv.Itoa(port)
+ if s.host != own || s.cookie != "" || s.auth != "" || s.origin != "http://"+own || s.path != "/api/chat" || s.query != "x=1" || s.body != `{"q":1}` {
+ t.Fatalf("the service saw %+v", s)
+ }
+ if w.Header().Get("Set-Cookie") != "" || w.Header().Get("Referrer-Policy") != "no-referrer" || !strings.Contains(strings.Join(w.Header().Values("Content-Security-Policy"), ";"), "sandbox allow-scripts") {
+ t.Fatalf("the answer isn't shut in: %v", w.Header())
+ }
+ // a sandboxed frame's Origin: null goes as it is
+ r = httptest.NewRequest("GET", base, nil)
+ r.Header.Set("Origin", "null")
+ do(h, r)
+ if s := <-got; s.origin != "null" || s.path != "/" {
+ t.Fatalf("the frame's request: %+v", s)
+ }
+ // redirects stay under the page's address
+ if w := do(h, httptest.NewRequest("GET", base+"old", nil)); w.Header().Get("Location") != base+"new" {
+ t.Fatalf("redirect: %q", w.Header().Get("Location"))
+ }
+ <-got
+ if w := do(h, httptest.NewRequest("GET", base+"away", nil)); w.Header().Get("Location") != base+"there?a=1" {
+ t.Fatalf("absolute redirect: %q", w.Header().Get("Location"))
+ }
+ <-got
+ // none for a page without a service, nor for a made-up token
+ for _, u := range []string{pluginPagePrefix + tokOf(glance) + "/" + pageServiceDir + "/", pluginPagePrefix + strings.Repeat("0", 32) + "/" + pageServiceDir + "/"} {
+ if w := do(h, httptest.NewRequest("POST", u, nil)); w.Code == 200 {
+ t.Errorf("%s forwarded: %d", u, w.Code)
+ }
+ }
+ select {
+ case s := <-got:
+ t.Fatalf("the service was asked %+v", s)
+ default:
+ }
+ // the service down: a 502 that says so
+ svc.Close()
+ if w := do(h, httptest.NewRequest("GET", base, nil)); w.Code != http.StatusBadGateway {
+ t.Fatalf("service down: %d", w.Code)
+ }
+}
diff --git a/internal/plugin/page.go b/internal/plugin/page.go
index 786e086de..931ceb1b7 100644
--- a/internal/plugin/page.go
+++ b/internal/plugin/page.go
@@ -38,6 +38,54 @@ 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), which magpie web forwards under
+ // the page's own address; nil when it names none.
+ Service *ServiceSpec
+}
+
+// ServiceSpec is where a page's service listens: 127.0.0.1 on Port, or on
+// the plugin's option PortOption when the user has set it to a port.
+type ServiceSpec struct {
+ Port int
+ PortOption string
+}
+
+// ServicePort is the port s listens on, by the plugin's options.
+func (s *ServiceSpec) ServicePort(options map[string]any) int {
+ if s == nil {
+ return 0
+ }
+ if s.PortOption != "" {
+ if p, ok := portOf(options[s.PortOption]); ok {
+ return p
+ }
+ }
+ return s.Port
+}
+
+func portOf(v any) (int, bool) {
+ var f float64
+ switch n := v.(type) {
+ case float64:
+ f = n
+ case int:
+ f = float64(n)
+ case int64:
+ f = float64(n)
+ case json.Number:
+ x, err := n.Float64()
+ if err != nil {
+ return 0, false
+ }
+ f = x
+ default:
+ return 0, false
+ }
+ if f != float64(int(f)) || f < 1 || f > 65535 {
+ return 0, false
+ }
+ return int(f), true
}
// PanelSpec is a panel a plugin adds to one of magpie's own pages: a
@@ -139,15 +187,20 @@ func Window(target string) (w *WindowSpec, only bool) {
Replaces string `json:"replaces"`
ID string `json:"id"`
Menu string `json:"menu"`
+ Service *struct {
+ Port any `json:"port"`
+ PortOption string `json:"portOption"`
+ } `json:"service"`
}
var pkg struct {
Main string `json:"main"`
Exports json.RawMessage `json:"exports"`
Magpie struct {
- Page *part `json:"page"`
- Panels []part `json:"panels"`
- Actions []part `json:"actions"`
- Permissions []string `json:"permissions"`
+ Page *part `json:"page"`
+ Panels []part `json:"panels"`
+ Actions []part `json:"actions"`
+ Permissions []string `json:"permissions"`
+ Options map[string]any `json:"options"`
} `json:"magpie"`
}
if json.Unmarshal(b, &pkg) != nil {
@@ -166,6 +219,17 @@ func Window(target string) (w *WindowSpec, only bool) {
if r := strings.TrimSpace(pg.Replaces); slices.Contains(Replaceable, r) {
p.Replaces = r
}
+ if sv := pg.Service; sv != nil {
+ port, _ := portOf(sv.Port)
+ opt := strings.TrimSpace(sv.PortOption)
+ if port == 0 && opt != "" {
+ // the option's default, in the package's magpie.options
+ port, _ = portOf(pkg.Magpie.Options[opt])
+ }
+ if port > 0 || opt != "" {
+ p.Service = &ServiceSpec{Port: port, PortOption: opt}
+ }
+ }
w.Page = p
}
}