plugin

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 24 Imported by: 0

README

mygo-plugin

简体中文

A native plugin host for MyGo apps: pure Go, in-process, no WebView. A plugin is a plugin.json plus a JavaScript or TypeScript module, run by moejs in a runtime of its own; the interface is still drawn by the host with MyGo's native UI.

This is not another WebView plugin container. A plugin gets no DOM and cannot draw the interface: it provides data, and the host decides how to show it. However heavy a plugin is, the app stays a MyGo app.

The plugin.json shape is the one MyGo Music uses, so existing plugins, such as the NetEase one, load unchanged.

Why a separate project

MyGo's own mygo.Plugin is a compile-time capability module: a Go service plus an npm package, registered with mygo.Use, callable only from trusted pages. It suits official capabilities (fetch, sqlite, terminal), not installable third-party plugins.

MyGo Music has a complete third-party plugin runtime, but it lives in internal/plugin, tied to its music types, and other apps cannot take it. This repository extracts the host: manifest, install, permissions, runtime, limits and CLI, with no dependency on music.

What it does

  • One moejs runtime per plugin, with its own heap and event loop
  • ES modules, async/await, TypeScript (when main ends in .ts)
  • host API: storage, crypto (MD5 / AES-ECB), language, setting, openURL, signInPrompt
  • fetch limited to permissions.network hosts; no permission means no network
  • Call timeouts, a 256 MiB memory limit, and automatic restart when stuck
  • Install from a folder or a ZIP; ZIP path traversal and size limits; List / Uninstall
  • mygo-plugin CLI: check, pack, new, list
  • Manifest JSON Schema: spec/plugin.schema.json

Quick start

import plugin "github.com/yxxbc/mygo-plugin"

p, err := plugin.Load("plugins/netease-haruhikage", plugin.Options{
    AppVersion: "0.1.26",
    DataDir:    filepath.Join(configDir, "mygo-plugin"),
    Host: plugin.Host{
        Language:     func() string { return "zh-CN" },
        OpenURL:      func(u string) error { return mygo.Shell.OpenExternal(u) },
        SignInPrompt: func(id string, p plugin.SignInPrompt) { showQR(p.QR, p.Text) },
    },
})
if err != nil {
    return err
}
defer p.Close()

var result struct {
    Tracks []struct {
        ID   string `json:"id"`
        Name string `json:"name"`
    } `json:"tracks"`
}
err = p.Call("search", map[string]any{"query": "周杰伦", "kind": "tracks", "offset": 0}, &result)

Options.DataDir is required and must belong to the app: the same plugin installed in two apps must not share its session and storage.

Call's contract belongs to the app, not to this layer: whatever a plugin exports, the app calls. MyGo Music's source contract (search / browse / stream / lyrics / signIn, ...) is one such contract, and existing plugins work with it directly.

The native boundary

A plugin cannot touch the host's UI tree. The host builds its sidebar from plugin.json's navigation; when the listener opens an entry:

  • with page: call the plugin's browse({ page }), get data such as { title, sections: [...] }, and draw it with MyGo's native components
  • with builtin: show the host's own page (home, liked, podcasts, ...)

The playback data plane stays in Go: a plugin's stream returns only { url, headers, type }; the host downloads, decodes and plays it, so audio bytes never cross into JavaScript. Lyrics work the same way: the plugin returns text, the host lays it out.

MyGo already separates trusted pages from untrusted ones: a plugin UI that needs HTML can run in a WebView with PageOptions{Untrusted: true}, where it calls no Go method and reaches only what the app's handlers allow. This host is for plugins that don't need HTML: native UI is drawn in Go, so third-party code cannot draw it. A plugin here has no page, no bridge and no DOM; it sees only the host functions its manifest declares, and the host renders its data with native views.

The threat model, and the questions a framework-level boundary would have to answer, are in docs/trust-model.md.

That is where the performance comes from. moejs calls take microseconds, but the real saving is not putting audio, covers and lyrics through JSON. Keep calls coarse; don't build a universal RPC.

Icons are names in the host's icon set (calendar, star, playlist, ...), not files. On macOS a host can draw Apple's SF Symbols with plugins/sfsymbols; other platforms use their own fallback set. Plugins should not ship SVG, or every host has to deal with rasterization and design consistency.

Host API

Name What it does
host.platform / host.arch The host's platform
host.dir / host.dataDir The plugin's folder / data folder
host.storage.get/set/remove Per-plugin JSON KV, written to storage.json
host.crypto.md5 / host.crypto.aesEcbEncrypt Hex output, PKCS#7 padding
host.language() A BCP 47 language tag
host.setting(key) The value the listener gave this plugin's setting
host.openURL(url) http/https only
host.signInPrompt({ qr, text }) What to show while signing in
host.spawn Starts no programs in this version; calling it returns an error

permissions.process is parsed but not executed by this host. A host that runs programs should implement it, and keep it deny-by-default.

Permissions

{
  "permissions": {
    "network": ["music.163.com", "interfacepc.music.163.com"],
    "process": ["bin/helper-*"]
  }
}
  • Empty network: fetch has no network
  • example.com matches exactly; *.example.com matches subdomains; * allows everything
  • The allowlist is checked on every request, redirects included
  • process is a declaration, not a grant

Installing and distributing

plugin.InstallDir(src, pluginsDir)   // from a folder
plugin.InstallZip(zip, pluginsDir)   // from a ZIP; plugin.json at the root or in the one folder
plugin.List(pluginsDir)
plugin.Uninstall(pluginsDir, id)     // keeps data, so a reinstall keeps the session
mygo-plugin check -app-version 0.1.26 ./my-plugin
mygo-plugin pack -o my-plugin.zip ./my-plugin
mygo-plugin new my-plugin
mygo-plugin list ~/Library/Application\ Support/MyApp/plugins

Signatures, a registry index and installing straight from a GitHub release are not done yet; see the roadmap. Don't build a review backend for v0.1.

Limits

  • Memory: 256 MiB by default; going over interrupts the runtime, and the next call restarts it
  • Time: 30s per call by default; code stuck in JavaScript is terminated
  • One runtime per plugin; calls enter that runtime one at a time
  • import is not available (a single-file module); bundle first if you need several files

Development

go test ./...
go vet ./...

# Verify with a real plugin (not run in CI)
MYGO_PLUGIN_REAL=../mygo-music-netease MYGO_PLUGIN_NETWORK=1 go test -run TestReal -v

Roadmap

  • Install from a GitHub release / topic, with a deeplink
  • Ed25519 signatures and install verification
  • A real implementation of the process permission (allowlist plus a grant UI)
  • A static registry index (GitHub as the source, JSON generated by CI)
  • Generate host.d.ts from the host's Go contract, and a mock host test package
  • A standard icon name table with cross-platform fallbacks

Credits and license

MIT. The plugin.json field shape is compatible with MyGo Music's plugins; this repository is an independent implementation and contains no code from MyGo Music. MyGo is egoist/mygo (MIT).

Documentation

Overview

Package plugin hosts third-party plugins in MyGo apps.

A plugin is a folder with a plugin.json and a JavaScript or TypeScript module. The host reads it, compiles it once, and runs it in a moejs runtime of its own, so a plugin never shares a runtime, a heap or an event loop with another. The app calls exports by name and gets JSON values back; the plugin reaches the app only through the host global, whose permissions the manifest declares.

The manifest is the one MyGo Music uses, so its plugins load here unchanged.

Index

Constants

View Source
const (
	// MaxArchive is the largest accepted zip.
	MaxArchive = 1 << 30
	// MaxUnpacked is the largest a zip may unpack to.
	MaxUnpacked = 2 << 30
	// MaxFiles is the most files a zip may hold.
	MaxFiles = 50000
)
View Source
const (
	// DefaultMemoryLimit is what one plugin may keep, in bytes.
	DefaultMemoryLimit = 256 << 20
	// DefaultCallTimeout is how long one call may take.
	DefaultCallTimeout = 30 * time.Second
)
View Source
const DefaultMain = "index.js"

DefaultMain is the module a manifest names when it doesn't.

Variables

View Source
var (
	// ErrSignIn says the listener has to sign in for this.
	ErrSignIn = errors.New("sign in first")
	// ErrSetup says a setting the plugin needs is missing.
	ErrSetup = errors.New("the plugin needs setting up")
	// ErrUnavailable says what was asked for can't be had.
	ErrUnavailable = errors.New("not available")
	// ErrUnsupported says the plugin doesn't do this.
	ErrUnsupported = errors.New("not supported by this plugin")
)
View Source
var ErrInstalled = errors.New("a plugin with this id is already installed")

ErrInstalled says a plugin with that id is already installed.

Functions

func CompareVersions

func CompareVersions(a, b string) (int, error)

CompareVersions compares two versions as 0.1.8: -1 when a is older, 0 when they are the same, and 1 when a is newer.

func Pack

func Pack(dir string, w io.Writer) error

Pack writes the plugin in dir as a zip, with plugin.json at its root.

func Uninstall

func Uninstall(pluginsDir, id string) error

Uninstall removes the plugin's folder. Its data stays, so installing it again keeps the listener's settings and session.

Types

type Host

type Host struct {
	// Language is the listener's language, as a BCP 47 tag: zh-CN, en.
	Language func() string
	// OpenURL opens a web page in the listener's browser.
	OpenURL func(url string) error
	// SignInPrompt shows what a plugin wants shown as it signs in.
	SignInPrompt func(pluginID string, prompt SignInPrompt)
	// Setting is the value the listener gave a setting of the plugin.
	Setting func(pluginID, key string) string
	// Logf receives what a plugin logs. Nil logs to the standard logger.
	Logf func(format string, args ...any)
}

Host is what a plugin reaches of the app. The zero value reaches nothing and logs to the standard logger.

type Manifest

type Manifest struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Version     string `json:"version,omitempty"`
	Author      string `json:"author,omitempty"`
	Homepage    string `json:"homepage,omitempty"`
	// Main is the module to run, relative to the plugin's folder.
	Main string `json:"main,omitempty"`
	// MinAppVersion is the oldest host version that can run the plugin.
	MinAppVersion string `json:"minAppVersion,omitempty"`
	// Playback tells the host how the plugin plays: "stream" when it answers
	// a URL the host fetches and plays itself, as MyGo Music's sources do.
	Playback    string       `json:"playback,omitempty"`
	Permissions Permissions  `json:"permissions"`
	Settings    []Setting    `json:"settings,omitempty"`
	Navigation  []Navigation `json:"navigation,omitempty"`
}

Manifest is a plugin's plugin.json.

func Inspect

func Inspect(dir, appVersion string) (*Manifest, []string, error)

Inspect reads and compiles a plugin without running it: what plugin.json says, and the exports the host can call.

func InstallDir

func InstallDir(src, pluginsDir string) (*Manifest, error)

InstallDir copies the plugin in src into pluginsDir, under its id. It doesn't replace a plugin that's already there.

func InstallZip

func InstallZip(path, pluginsDir string) (*Manifest, error)

InstallZip unpacks the zip into pluginsDir, under its id. plugin.json is at the zip's root, or in its one folder, as GitHub's archives have it. It doesn't replace a plugin that's already there.

func List

func List(pluginsDir string) ([]*Manifest, error)

List reads the manifests of the plugins in pluginsDir, leaving out the ones that don't read: one broken plugin shouldn't hide the others.

func ReadManifest

func ReadManifest(dir string) (*Manifest, error)

ReadManifest reads the plugin.json in dir, fills in what it leaves out, and checks it.

func (*Manifest) Validate

func (m *Manifest) Validate() error

Validate says what's wrong with the manifest, or nil.

type Navigation struct {
	Title string `json:"title"`
	// Page is the name the host asks the plugin's browse export for.
	Page string `json:"page,omitempty"`
	// Builtin names a page the host draws itself.
	Builtin string `json:"builtin,omitempty"`
	// Icon names one of the host's icons, not a file.
	Icon string `json:"icon,omitempty"`
}

Navigation is an entry in the host's sidebar.

type NeedsNewerApp

type NeedsNewerApp struct {
	Plugin  string // its name
	Version string // the oldest host version it works with
}

NeedsNewerApp is why a plugin doesn't load: it needs a newer host.

func (*NeedsNewerApp) Error

func (e *NeedsNewerApp) Error() string

type Options

type Options struct {
	// AppVersion is the host's version, which minAppVersion is checked
	// against. Empty loads any plugin, as in development.
	AppVersion string
	// DataDir is where the host keeps the plugins' data, one folder per
	// plugin. It is required, and should belong to the app, so that two
	// apps with the same plugin don't share its storage.
	DataDir string
	// Host is what the app offers the plugin.
	Host Host
	// MemoryLimit is what one runtime may keep. Zero means 256 MiB.
	MemoryLimit int64
	// CallTimeout is how long one call may take. Zero means 30 seconds.
	CallTimeout time.Duration
	// HTTPClient sends fetch's requests. Nil means an http.Client with a
	// ten minute timeout.
	HTTPClient *http.Client
}

Options say where a plugin keeps its data and what it may reach.

type Permissions

type Permissions struct {
	// Network lists the hosts fetch may reach: example.com, *.example.com
	// for its subdomains, or * for any. Empty reaches nothing.
	Network []string `json:"network,omitempty"`
	// Process lists the programs the plugin may start, once the listener
	// grants it. This version declares them but doesn't start any: a host
	// that does reads them from here.
	Process Programs `json:"process,omitempty"`
}

Permissions are what a plugin asks for beyond its own folder and data.

type Plugin

type Plugin struct {
	// contains filtered or unexported fields
}

Plugin is one plugin, compiled and ready to run. It starts on the first call, in a runtime of its own, and starts over after it gets stuck.

func Discover

func Discover(dir string, opts Options) []*Plugin

Discover loads every plugin folder in dir. One that doesn't load is logged and left out, so it can't take the others with it.

func Load

func Load(dir string, opts Options) (*Plugin, error)

Load reads and compiles the plugin in dir, without running it.

func (*Plugin) Call

func (p *Plugin) Call(method string, args, out any) error

Call calls an export with args and decodes its answer into out, unless out is nil. An export the module doesn't have is ErrUnsupported.

func (*Plugin) CallWithin

func (p *Plugin) CallWithin(timeout time.Duration, method string, args, out any) error

CallWithin is Call with a timeout of its own.

func (*Plugin) Can

func (p *Plugin) Can(method string) bool

Can reports whether the module exports the function.

func (*Plugin) Close

func (p *Plugin) Close()

Close stops the plugin. It starts again on the next call.

func (*Plugin) DataDir

func (p *Plugin) DataDir() string

DataDir is where the plugin keeps its data.

func (*Plugin) Dir

func (p *Plugin) Dir() string

Dir is the plugin's folder.

func (*Plugin) Exports

func (p *Plugin) Exports() []string

Exports lists the functions the module exports, without running it.

func (*Plugin) ID

func (p *Plugin) ID() string

ID is the plugin's identifier.

func (*Plugin) Manifest

func (p *Plugin) Manifest() Manifest

Manifest is what plugin.json says.

type Programs

type Programs []string

Programs is a permission's list of programs: names on PATH, paths from the plugin's folder, patterns as filepath.Match has them, or true for any.

func (Programs) Any

func (p Programs) Any() bool

Any reports whether the plugin may start any program.

func (*Programs) UnmarshalJSON

func (p *Programs) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts a list of programs, or true for any.

type Setting

type Setting struct {
	Key   string `json:"key"`
	Label string `json:"label"`
	Help  string `json:"help,omitempty"`
	Link  string `json:"link,omitempty"`
}

Setting is a value the listener fills in, which the plugin reads with host.setting.

type SignInPrompt

type SignInPrompt struct {
	QR   string `json:"qr,omitempty"`
	Text string `json:"text,omitempty"`
}

SignInPrompt is what a plugin wants shown while the listener signs in.

Directories

Path Synopsis
cmd
mygo-plugin command
Command mygo-plugin checks, packs and starts plugins for MyGo apps.
Command mygo-plugin checks, packs and starts plugins for MyGo apps.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL