Files
magpie/internal/plugin/page.go
T
yetone 64b0f3a201 plugins: a community plugin's own page in magpie's window, shut in a sandboxed frame (P4)
A plugin's package.json may declare magpie.page {title, file, icon} and
magpie.permissions.reads. While the plugin is on, its page gets a tab in a
"Plugins" group after the built-in pages, drawn in an iframe sandboxed to
allow-scripts only (an opaque origin: no cookie, no storage, no parent).
Its files come from /_magpie/plugin/<token>/ (HMAC of the spec with a
per-process secret) under a CSP with connect-src 'none' and
frame-ancestors 'self'; a path that leaves the page's folder, a symlink
out, or an off plugin's token is refused. The window's postMessage bridge
answers only that frame (event.source checked) with theme and language,
the plugin's own options.get/set (throttled), and the reads it declared;
any other read is refused in the window and again by the server, and no
read carries a secret. /api refuses Origin: null and frame/iframe
fetch-dest requests (noFramedAPI), so the frame never reaches the GUI's
API even with the cookie. A page that throws or never says hello shows
the kernel's broken-page state with Try again. The Plugins page shows the
page and what it reads before the plugin is turned on.

Docs: gui-shell.md, plugin-runtime.md (P4 section), site docs en/zh/ja
with an example plugin; i18n zh, zh-TW, ja, de; fixture in
internal/gui/testdata/page-plugin.

Run (worktree at base 4df1ba0c6, -p 2, one package at a time):
- go test -count=1 -timeout 45m: internal/gui ok, internal/plugin ok,
  internal/pluginrt ok, plugins/... (budget groups middleware otel redact
  rotation search) ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean.
- Playwright (chromium + webkit, 5 languages, narrow widths): plugin-page 4/4,
  plugin-kernel 4/4, builtins 4/4, i18n-keys, gui-de, gui-ja, gui-zh-tw 3/3,
  plugin-middleware 24/24, plugin-own-icon 22/22, plugin-options 22/22,
  plugin-local 8/8, plugin-agent 22/22, click-scroll 22/22.

Broken by hand, each went red: CSP without connect-src; apiFramed always
false; the server's read check removed; the noFramedAPI wrap removed from
api.go (red through the real Handler); inside() letting every path
through; CORP same-origin re-added; in JS the client read check removed,
the ev.source check removed, and allow-same-origin added to the sandbox.
Without the Array.isArray guard on /api/plugin-pages, plugin-kernel,
builtins and plugin-middleware/own-icon/options went red (their mocks
answer a non-list) - that was found by the run, then fixed.

Real use: built magpie, `magpie web` on 127.0.0.1:3472 (gateway 3471) in a
sandbox HOME with the example plugin added. curl: the page file loads
with the CSP and no cookie, traversal and a bad token are 404, /api with
Origin: null or Sec-Fetch-Dest: iframe is 403 even with the cookie, an
undeclared read 403, a declared one 200. Chromium and WebKit at 1100 and
420: the page draws its declared read, the probe's fetch/absolute
fetch/top access/undeclared read are all refused, an <img> of /api is
refused, no page errors. Real use found that a
Cross-Origin-Resource-Policy: same-origin header blocked the frame's own
files (its origin is opaque); it is gone and a test guards it.

Not tried: the desktop (Wails) window. Market cards of plugins not yet
installed don't show a page's reads. The Playwright suite mirrors the
CSP in a mock route rather than the Go server (the Go tests and real use
cover the server).
2026-10-15 22:36:59 +08:00

142 lines
4.2 KiB
Go

package plugin
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
)
// PageSpec is the page a plugin adds to magpie's window: package.json's
// magpie.page, and the reads magpie.permissions asks for.
type PageSpec struct {
Title string // "" when it names none
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
// Reads are the reads the page asked for that magpie has (PageReads),
// in the order asked.
Reads []string
}
// 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"}
// WindowPage is the page a plugin at target adds to magpie's window, or nil:
// package.json's magpie.page {title, file, icon}. A file outside the
// plugin's folder is no page. only is whether it is nothing else: no
// OpenCode plugin for the host to load (no main, no exports).
func WindowPage(target string) (p *PageSpec, 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
}
var pkg struct {
Main string `json:"main"`
Exports json.RawMessage `json:"exports"`
Magpie struct {
Page *struct {
Title string `json:"title"`
File string `json:"file"`
Icon string `json:"icon"`
} `json:"page"`
Permissions []string `json:"permissions"`
} `json:"magpie"`
}
if json.Unmarshal(b, &pkg) != nil || pkg.Magpie.Page == nil {
return nil, false
}
pg := pkg.Magpie.Page
file, ok := inside(target, pg.File)
if !ok || !strings.HasSuffix(strings.ToLower(file), ".html") {
return nil, false
}
p = &PageSpec{Title: strings.TrimSpace(pg.Title), 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)
}
}
for _, r := range pkg.Magpie.Permissions {
if slices.Contains(PageReads, r) && !slices.Contains(p.Reads, r) {
p.Reads = append(p.Reads, r)
}
}
return p, pkg.Main == "" && len(pkg.Exports) == 0
}
// 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
}
// PageFile is the file at rel among a page's files, if it is one: inside
// the page's folder, and a file.
func (p *PageSpec) PageFile(rel string) (string, bool) {
f, ok := inside(p.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. One whose
// page is all it has is never loaded by the host, so the host goes on as
// it was; any other 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)
}
if p, only := WindowPage(t); p == 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)
}