plugin

package module
v0.1.0 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

MyGo 应用的原生插件宿主:纯 Go、进程内、无 WebView。插件是 plugin.json 加一个 JavaScript / TypeScript 模块,由 moejs 在每个插件自己的运行时里跑;界面仍由宿主用 MyGo 的原生 UI 绘制。

这不是又一个 WebView 插件容器。插件拿不到 DOM,也画不了界面;它提供数据,宿主决定怎么画。这样插件再重,应用也还是 MyGo 的应用。

plugin.json 与 MyGo Music 的插件同形,现有的网易云等插件可以直接加载。

为什么单独做

MyGo 自带的 mygo.Plugin 是编译期的能力模块:Go service 加 npm 包,mygo.Use 注册,只有可信页面能调。它适合官方能力(fetch、sqlite、terminal),不适合安装第三方插件。

MyGo Music 有一套完整的第三方插件运行时,但它在 internal/plugin 里,和音乐类型绑死,别的应用拿不走。这个仓库把宿主抽出来:manifest、安装、权限、运行时、限制、CLI,全都不依赖音乐。

能力

  • 每个插件一个 moejs runtime,独立堆、独立事件循环,互不影响
  • ES modules、async/await、TypeScript(main 为 .ts 时)
  • host API:storage、crypto(MD5 / AES-ECB)、language、setting、openURL、signInPrompt
  • fetch 按 permissions.network 的 host allowlist 放行;没有权限就完全断网
  • 调用超时、256 MiB 内存上限、卡死自动重启
  • 从文件夹或 ZIP 安装;ZIP 防穿越、限大小;List / Uninstall
  • mygo-plugin CLI:check、pack、new、list
  • manifest JSON Schema:spec/plugin.schema.json

快速开始

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 必须由应用指定,并且按应用区分:同一个插件装进两个应用,不能共享 session 和 storage。

Call 的约定由应用定,不在这层:插件导出什么,应用就调什么。MyGo Music 的来源契约(search / browse / stream / lyrics / signIn …)是其中一个已存在的契约,现有插件直接可用。

原生的边界

插件不能操作宿主的 UI 树。宿主从 plugin.json 的 navigation 生成侧栏,用户点某一项时:

  • 有 page:调用插件的 browse({ page }),拿回 { title, sections: [...] } 之类的数据,用 MyGo 原生组件画
  • 有 builtin:宿主自己的页面(首页、喜欢、播客…)

播放的数据面留在 Go:插件 stream 只返回 { url, headers, type },宿主自己下载、解码、播放,音频字节不经过 JS。歌词同理,插件返回文本,宿主排版。

这就是性能的关键:moejs 的调用是微秒级,但真正的省是在于不把音频、封面、歌词塞进运行时的 JSON。保持调用粗粒度,别做万能 RPC。

图标不是文件,是宿主图标集里的名字(calendar、star、playlist…)。macOS 上宿主可以用 plugins/sfsymbols 画系统 SF Symbols,其他平台用自己的回退集。插件不该带 SVG,否则每个宿主都要处理栅格化和设计一致性。

Host API

名称 说明
host.platform / host.arch 宿主平台
host.dir / host.dataDir 插件目录 / 插件数据目录
host.storage.get/set/remove 每插件独立的 JSON KV,落盘到 storage.json
host.crypto.md5 / host.crypto.aesEcbEncrypt 十六进制输出,PKCS#7 填充
host.language() BCP 47 语言标签
host.setting(key) 用户给这个插件的设置值
host.openURL(url) 只允许 http/https
host.signInPrompt({ qr, text }) 登录时给宿主显示
host.spawn 本版本不启动进程,调用会报错

permissions.process 会被解析,但当前宿主不执行;需要起进程的宿主自己实现,并保持 deny-by-default。

权限

{
  "permissions": {
    "network": ["music.163.com", "interfacepc.music.163.com"],
    "process": ["bin/helper-*"]
  }
}
  • network 为空:fetch 不接网络
  • example.com 精确匹配;*.example.com 匹配子域;* 全放行
  • allowlist 在每次请求(含重定向)时检查
  • process 是声明,不是自动授权

安装与分发

plugin.InstallDir(src, pluginsDir)   // 从文件夹
plugin.InstallZip(zip, pluginsDir)   // 从 ZIP,plugin.json 在根或唯一子目录
plugin.List(pluginsDir)
plugin.Uninstall(pluginsDir, id)     // 保留数据,重装后 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

签名、registry 索引、从 GitHub release 直接安装还没做;见路线图。别在 v0.1 就自建审核后台。

限制

  • 内存:默认 256 MiB,超过会被中断,下次调用重启
  • 时间:默认 30s 一次调用;卡死在 JS 里会被终止
  • 一个插件一个 runtime;调用串行进入该 runtime
  • 插件 import 不可用(单文件模块);需要多文件时先打包

开发

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

# 用真实插件验证(不会进 CI)
MYGO_PLUGIN_REAL=../mygo-music-netease MYGO_PLUGIN_NETWORK=1 go test -run TestReal -v

路线图

  • 从 GitHub release / topic 安装,deeplink
  • Ed25519 签名与安装校验
  • 进程权限的真实实现(allowlist + 授权 UI)
  • 静态 registry index(GitHub 即源,CI 生成 JSON)
  • 从宿主 Go 契约生成 host.d.ts,加 mock host 测试包
  • 标准图标名表与跨平台回退

来源与许可

MIT。plugin.json 的字段形状与 MyGo Music 的插件兼容;本仓库是独立实现,不包含 MyGo Music 的代码。MyGo 是 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