aigcfree (Discord DM) runs `magpie web --addr 0.0.0.0:3430` on an Ubuntu
server behind nginx and opens it from a Windows PC. Plugins -> 对话
(@magpie-community/page-chat) showed "127.0.0.1 refused to connect": the
page sends its frame to the chat server on 127.0.0.1, which in that
browser is the Windows PC.
A plugin now declares its page's service (package.json
magpie.page.service {port, option}: the port, or the plugin option that
holds it, from its plugins.json options; plugin.ServiceSpec). Served to a
browser (isWeb), /api/plugin-pages gives the page `service`:
_magpie/service/ under its token, and the bridge hands the frame
magpie.service as an absolute address. The desktop window and slot pages
get none, and the routes answer 404 there, so the local path is as before.
servePageService reverse-proxies /_magpie/plugin/<token>/_magpie/service/…
to 127.0.0.1:<port>. The service stays on loopback. The way in is the
page's own: the per-run token that only a signed-in /api hands out,
behind AllowGuard. Nothing is weakened:
- Host is set to 127.0.0.1:<port>, which the service's rebinding check
wants.
- The window's cookie is taken off.
- Origin must be absent or null (403 otherwise).
- Set-Cookie is dropped.
- Every reply is sandboxed (sandbox allow-scripts; frame-ancestors
'self'), with Referrer-Policy no-referrer and nosniff.
- The gateway's own port is never served, since a request from this
server is loopback and the gateway takes that without a key.
- Event streams flush as they come (FlushInterval -1, X-Accel-Buffering:
no for nginx). webCompressed no longer gzips text/event-stream, which
held a stream back until gzip's buffer filled.
- A redirect to the service's own address is made relative.
- The entry starts the plugin host as the page's HTML does (pageHost).
- A service not up yet answers its frame with a 502 page that tries
again in 2s.
page-chat 0.1.2 (magpie-community/plugins 4a46212, on dist) declares the
service, goes to magpie.service when given one (else 0.1.1's path:
127.0.0.1 on loopback, the SSH-tunnel note from elsewhere), and asks
api/… by relative address.
Docs: plugin-runtime.md P4 (the page row), gui-shell.md (no gzip for event
streams).
Tests: TestPluginPageServiceListedToBrowserOnly, TestPluginPageServiceSpec,
TestPluginPageServiceProxied (through webHandler: Host, cookie, Set-Cookie,
CSP, escaped path and query, foreign Origin 403, made-up token 404,
redirects, SSE first event before the end and not gzipped),
TestPluginPageServiceDown, TestServiceLocation; plugin-page.test.cjs
checks magpie.service in a browser page and its absence in a slot.
Run at 276683d85, this change on origin/main e61e10535. It was rebased
since onto c1660481c, a one-line WorkBuddy mover min in internal/provider.
181fd0a68
(another session's proxy, path _service/, {portOption}) is reverted
there by 3870ddf0a, and nothing of it is left:
- go test ./internal/gui/ ./internal/plugin/ -timeout 45m, native on the
Windows box: every new test ok. 8 reds, none in code this touches:
- 6 fail the same at origin/main c1660481c, run there by name:
TestGatewayHeldByAContainer, TestLodyImportHandoff,
TestImportStatusUnreadableIsUnknown, TestAionUiImportRow,
TestUpdateThatWontStart, TestPiPackage. All are in #4115.
- TestLoadConcurrentWithSavesAndEdits is red 2 of 3 alone here and red
at c1660481c too (a rename "Access is denied"); it is in #1827.
- TestDesktopSessionTitlesOnPages passes alone (3 of 3). In the package
run it listed the box's real WSL Codex session. Filed as #4185.
- Earlier, at bc247a8cc, on mote: the new Go tests, and go vet of both
packages.
- Not run at this tree: the full go test ./... . mote was at load 300+
with three other sessions' full suites, and the Linux box had one. A
run at an older base (fa5ff2fec) had 25 packages ok, internal/agent
among them, and none red when it was stopped for the rebase.
- gofmt -l: clean. go vet ./internal/gui ./internal/plugin: darwin on
mote, native Windows on xiaomi-gpu. A Linux vet from mote fails in wails'
cgo files, and in WSL for lack of gtk4/webkitgtk-6.0 headers, both
unrelated to this change; CI vets Linux with its headers.
- plugin-page.test.cjs on the Windows box, both engines: WebKit 3/3.
Chromium's first test is #4180, which fails the same on origin/main
f463a8aaf. The next commit fixes #4180 at its cause.
- Real: a sandbox magpie web on mote (0.0.0.0:3561, sandbox HOME,
MAGPIE_WEB_KEY, the real chat package from a folder, a fake gateway).
Playwright on the Windows box opened Plugins -> chat over the LAN in
Chromium and WebKit. The frame went to
http://mote.local:3561/_magpie/plugin/<tok>/_magpie/service/?theme=…
with origin null. Its fonts.css and style.css came through the proxy. A
sent message streamed back "remote chat works", and the fake gateway
logged both POSTs.
- From the Mac over the LAN: /api/plugin-pages without the cookie
gives 401. A made-up token gives 404. A foreign Origin gives 403.
POST api/chat without the chat token gives 403 (the service's own
check). mote.local:3563 directly is refused (loopback only).
- Before bun was reachable in the sandbox, the frame got the 502 retry
page.
- Broken by hand, each red then restored:
- Without the event-stream exclusion, the stream arrives gzipped.
- Without the Host rewrite, the cookie strip or the web gate, each
assertion is red.
- With the bridge's service dropped, plugin-page.test.cjs is red in
WebKit ("magpie.service").
Not tried:
- A real nginx in front.
- A WebSocket through the proxy (httputil handles the upgrade; the chat
page uses none).
- TLS (--tls-cert).
- The desktop app with page-chat 0.1.2: its fallback is 0.1.1's path,
covered by the plugin's launcher tests.
370 lines
12 KiB
Go
370 lines
12 KiB
Go
package plugin
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// WindowSpec is what a plugin adds to magpie's window: its page
|
|
// (package.json's magpie.page), its panels in magpie's own pages
|
|
// (magpie.panels), the items it adds to magpie's menus (magpie.actions),
|
|
// and the reads magpie.permissions asks for, which its page and its
|
|
// panels share.
|
|
type WindowSpec struct {
|
|
Page *PageSpec // nil when it adds no page of its own
|
|
Panels []PanelSpec
|
|
// Actions are its items in magpie's menus, each opening its page;
|
|
// none without a page
|
|
Actions []ActionSpec
|
|
// Reads are the reads it asked for that magpie has (PageReads), in
|
|
// the order asked.
|
|
Reads []string
|
|
}
|
|
|
|
// PageSpec is a plugin's own page in magpie's window.
|
|
type PageSpec struct {
|
|
Title string // "" when it names none
|
|
// Titles are its title in other languages, by the window's language
|
|
// ("zh", "zh-TW", "ja", "de"): magpie.page.titles
|
|
Titles map[string]string
|
|
Icon string // a file in the page's folder, relative to it, or ""
|
|
File string // the page's HTML, inside the plugin's folder
|
|
Dir string // the folder the page's files are served from: File's
|
|
// 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
|
|
// part of that page, drawn by the plugin's HTML in a frame of its own.
|
|
type PanelSpec struct {
|
|
Slot string // one of PanelSlots
|
|
Title string // "" when it names none
|
|
Titles map[string]string
|
|
File string // the panel's HTML, inside the plugin's folder
|
|
Dir string // the folder the panel's files are served from: File's
|
|
}
|
|
|
|
// ActionSpec is an item a plugin adds to one of magpie's menus
|
|
// (ActionMenus). Picking it opens the plugin's page, which is told the
|
|
// action's id and the row it was picked on (magpie.onAction).
|
|
type ActionSpec struct {
|
|
ID string // its id among the plugin's actions: actionID
|
|
Menu string // one of ActionMenus
|
|
Title string // "" when it names none: the page's title then
|
|
Titles map[string]string
|
|
}
|
|
|
|
// ActionMenus are the menus a plugin's action can be in: a provider
|
|
// row's (the page is told the provider's id and name) and an agent row's
|
|
// (the agent's id and name). Nothing else of the row is told.
|
|
var ActionMenus = []string{"provider", "agent"}
|
|
|
|
// actionID is what an action's id is: short, of lower-case letters,
|
|
// digits and dashes, so the page can switch on it
|
|
var actionID = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,39}$`)
|
|
|
|
// maxActions is how many actions one plugin adds, at most.
|
|
const maxActions = 8
|
|
|
|
// PageReads are the reads a plugin's page can be granted, each in
|
|
// magpie.permissions. None of them carries a secret.
|
|
var PageReads = []string{"usage:summary", "providers:list"}
|
|
|
|
// PanelSlots are the places in magpie's own pages a plugin's panel can
|
|
// go: under the Agents page's list, at the end of the Usage page, on
|
|
// Settings' Plugins tab, and in a provider's editor (which tells the
|
|
// panel the provider's id and name).
|
|
var PanelSlots = []string{"agents", "usage", "settings", "provider"}
|
|
|
|
// Replaceable are the built-in pages a plugin's page can take the place
|
|
// of: the pages that are built-in plugins of their own.
|
|
var Replaceable = []string{"sessions", "library", "routing", "usage"}
|
|
|
|
// titles are a page's or a panel's titles by language, without the empty
|
|
// ones, or nil: magpie.page.titles {"zh": "…"}. title stays a string
|
|
// beside them, so a magpie that knows no titles still reads the package,
|
|
// and titles that aren't an object of strings leave the page as it was.
|
|
func titles(raw json.RawMessage) map[string]string {
|
|
var m map[string]any
|
|
if json.Unmarshal(raw, &m) != nil {
|
|
return nil
|
|
}
|
|
var out map[string]string
|
|
for k, x := range m {
|
|
v, _ := x.(string)
|
|
k, v = strings.TrimSpace(k), strings.TrimSpace(v)
|
|
if k == "" || v == "" || len(k) > 16 || len(out) == 16 {
|
|
continue
|
|
}
|
|
if out == nil {
|
|
out = map[string]string{}
|
|
}
|
|
out[k] = v
|
|
}
|
|
return out
|
|
}
|
|
|
|
// maxPanels is how many panels one plugin adds, at most.
|
|
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, 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
|
|
// can't be replaced. only is whether it is nothing else: no OpenCode
|
|
// plugin for the host to load (no main, no exports).
|
|
func Window(target string) (w *WindowSpec, only bool) {
|
|
st, err := os.Stat(target)
|
|
if err != nil || !st.IsDir() {
|
|
return nil, false
|
|
}
|
|
b, err := os.ReadFile(filepath.Join(target, "package.json"))
|
|
if err != nil {
|
|
return nil, false
|
|
}
|
|
type part struct {
|
|
Title string `json:"title"`
|
|
Titles json.RawMessage `json:"titles"`
|
|
File string `json:"file"`
|
|
Icon string `json:"icon"`
|
|
Slot string `json:"slot"`
|
|
Replaces string `json:"replaces"`
|
|
ID string `json:"id"`
|
|
Menu string `json:"menu"`
|
|
Service json.RawMessage `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"`
|
|
} `json:"magpie"`
|
|
}
|
|
if json.Unmarshal(b, &pkg) != nil {
|
|
return nil, false
|
|
}
|
|
w = &WindowSpec{}
|
|
if pg := pkg.Magpie.Page; pg != nil {
|
|
if file, ok := htmlInside(target, pg.File); ok {
|
|
p := &PageSpec{Title: strings.TrimSpace(pg.Title), Titles: titles(pg.Titles), File: file, Dir: filepath.Dir(file)}
|
|
// the icon is served with the page, so it sits in the page's folder
|
|
if icon, ok := inside(target, pg.Icon); ok {
|
|
if rel, err := filepath.Rel(p.Dir, icon); err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
|
p.Icon = filepath.ToSlash(rel)
|
|
}
|
|
}
|
|
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
|
|
}
|
|
}
|
|
for _, pn := range pkg.Magpie.Panels {
|
|
if len(w.Panels) == maxPanels {
|
|
break
|
|
}
|
|
slot := strings.TrimSpace(pn.Slot)
|
|
file, ok := htmlInside(target, pn.File)
|
|
if !ok || !slices.Contains(PanelSlots, slot) {
|
|
continue
|
|
}
|
|
w.Panels = append(w.Panels, PanelSpec{Slot: slot, Title: strings.TrimSpace(pn.Title), Titles: titles(pn.Titles), File: file, Dir: filepath.Dir(file)})
|
|
}
|
|
// an action opens the plugin's page, so a plugin with none has no
|
|
// action; an id given twice is the first's
|
|
for _, a := range pkg.Magpie.Actions {
|
|
if w.Page == nil || len(w.Actions) == maxActions {
|
|
break
|
|
}
|
|
id, menu := strings.TrimSpace(a.ID), strings.TrimSpace(a.Menu)
|
|
if !actionID.MatchString(id) || !slices.Contains(ActionMenus, menu) || slices.ContainsFunc(w.Actions, func(x ActionSpec) bool { return x.ID == id }) {
|
|
continue
|
|
}
|
|
w.Actions = append(w.Actions, ActionSpec{ID: id, Menu: menu, Title: strings.TrimSpace(a.Title), Titles: titles(a.Titles)})
|
|
}
|
|
if w.Page == nil && len(w.Panels) == 0 {
|
|
return nil, false
|
|
}
|
|
for _, r := range pkg.Magpie.Permissions {
|
|
if slices.Contains(PageReads, r) && !slices.Contains(w.Reads, r) {
|
|
w.Reads = append(w.Reads, r)
|
|
}
|
|
}
|
|
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) {
|
|
file, ok := inside(dir, rel)
|
|
if !ok || !strings.HasSuffix(strings.ToLower(file), ".html") {
|
|
return "", false
|
|
}
|
|
if st, err := os.Stat(file); err != nil || st.IsDir() {
|
|
return "", false
|
|
}
|
|
return file, true
|
|
}
|
|
|
|
// inside is rel joined to dir, if that stays inside dir: no "..", no
|
|
// absolute path, and no symbolic link out of it.
|
|
func inside(dir, rel string) (string, bool) {
|
|
rel = strings.TrimSpace(rel)
|
|
if rel == "" || filepath.IsAbs(rel) || strings.HasPrefix(rel, "/") || strings.Contains(rel, `\`) {
|
|
return "", false
|
|
}
|
|
clean := filepath.Clean(filepath.FromSlash(rel))
|
|
if clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) {
|
|
return "", false
|
|
}
|
|
full := filepath.Join(dir, clean)
|
|
realDir, err := filepath.EvalSymlinks(dir)
|
|
if err != nil {
|
|
return "", false
|
|
}
|
|
real, err := filepath.EvalSymlinks(full)
|
|
if err != nil {
|
|
return "", false
|
|
}
|
|
if r, err := filepath.Rel(realDir, real); err != nil || r == ".." || strings.HasPrefix(r, ".."+string(filepath.Separator)) {
|
|
return "", false
|
|
}
|
|
return full, true
|
|
}
|
|
|
|
// FileIn is the file at rel among the files served from dir (a page's
|
|
// or a panel's folder), if it is one: inside dir, and a file.
|
|
func FileIn(dir, rel string) (string, bool) {
|
|
f, ok := inside(dir, rel)
|
|
if !ok {
|
|
return "", false
|
|
}
|
|
if st, err := os.Stat(f); err != nil || st.IsDir() {
|
|
return "", false
|
|
}
|
|
return f, true
|
|
}
|
|
|
|
// SetPageOptions sets the options of a plugin from its page or a panel.
|
|
// One whose page and panels are all it has is never loaded by the host, so the host goes on as
|
|
// it was; any other (a middleware, an agent, a gateway hook, a provider) is SetOptions, which
|
|
// starts the host again for it.
|
|
func SetPageOptions(spec string, opts map[string]any) error {
|
|
t := Target(spec)
|
|
if mw, _ := Middleware(t); mw != "" {
|
|
return SetOptions(spec, opts)
|
|
}
|
|
if ag, _ := Agent(t); ag != "" {
|
|
return SetOptions(spec, opts)
|
|
}
|
|
// a gateway hook is handed the options the host loaded it with
|
|
if Gateway(t) != "" {
|
|
return SetOptions(spec, opts)
|
|
}
|
|
if w, only := Window(t); w == nil || !only {
|
|
return SetOptions(spec, opts)
|
|
}
|
|
listMu.Lock()
|
|
defer listMu.Unlock()
|
|
l := Load()
|
|
i := indexOf(l, spec)
|
|
if i < 0 {
|
|
return fmt.Errorf("no plugin %q", spec)
|
|
}
|
|
if len(opts) == 0 {
|
|
opts = nil
|
|
}
|
|
l.Plugins[i].Options = opts
|
|
return save(l)
|
|
}
|