Files
Reims-Go/pkg/pluginsdk/sdk.go
T
NwflowerandClaude Opus 5.5 44e2174fff fix: harden guest driver host APIs
- run elevated actions as fixed System32 tools instead of a hidden subcommand
- require a SHA-256 for plugin downloads
- keep records of secret files that could not be deleted, and never overwrite
  files the host did not create
- stop two concurrent requests from starting the same VM
- drop invalid endpoints instead of failing the whole VM list, and reject ssh
  users and IPv6 zones that could inject command-line text
- accept driver screenshots only at the requested path
- do not treat an unreadable guest phase as normal

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 09:07:46 -07:00

670 lines
19 KiB
Go

// Package pluginsdk provides a zero-dependency Go SDK for external L3 Sidecar
// plugins communicating via Content-Length framed JSON-RPC 2.0 over stdin/stdout
// while writing diagnostics and logs to stderr.
package pluginsdk
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
)
// PluginAPIVersion is the protocol version spoken by this SDK.
const PluginAPIVersion = "1.2.0"
// Handler handles one inbound JSON-RPC method from the Reims-Go host.
type Handler func(ctx context.Context, params json.RawMessage) (any, error)
// InitInfo contains initialization data received from the host during handshake.
type InitInfo struct {
PluginID string `json:"pluginId"`
PluginAPI string `json:"pluginApi"`
UIAPI string `json:"uiApi,omitempty"`
BridgeAPI string `json:"bridgeApi,omitempty"`
// Features lists stable host features (e.g. "bridge.vm.list",
// "slot.settings.plugin.panel"); check HasFeature instead of comparing versions.
Features []string `json:"features,omitempty"`
DataDir string `json:"dataDir"`
Locale string `json:"locale,omitempty"`
FallbackChain []string `json:"fallbackChain,omitempty"`
L10nBundle map[string]string `json:"l10nBundle,omitempty"`
}
// HasFeature reports whether the host advertised feature in the handshake.
func (i InitInfo) HasFeature(feature string) bool {
for _, f := range i.Features {
if f == feature {
return true
}
}
return false
}
// LocaleChangedEvent is delivered via the `plugin/localeChanged` notification
// whenever the user changes the Reims-Go interface language at runtime.
type LocaleChangedEvent struct {
Locale string `json:"locale"`
FallbackChain []string `json:"fallbackChain,omitempty"`
L10nBundle map[string]string `json:"l10nBundle,omitempty"`
}
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type envelope struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
// Server runs inside a Sidecar executable, serving host requests over stdin/stdout
// and issuing reverse Host API calls back to Reims-Go.
type Server struct {
in *bufio.Reader
out io.Writer
mu sync.Mutex
handlers map[string]Handler
pending map[string]chan envelope
writeMu sync.Mutex
nextID atomic.Uint64
initInfo InitInfo
caps map[string]any
onLocaleChanged func(LocaleChangedEvent)
}
// New creates a Sidecar SDK server bound to os.Stdin / os.Stdout.
func New() *Server {
return NewWithIO(os.Stdin, os.Stdout)
}
// NewWithIO creates a Sidecar SDK server over custom streams (useful for tests).
func NewWithIO(r io.Reader, w io.Writer) *Server {
s := &Server{
in: bufio.NewReaderSize(r, 64*1024),
out: w,
handlers: make(map[string]Handler),
pending: make(map[string]chan envelope),
caps: map[string]any{},
}
s.Handle("plugin/initialize", func(_ context.Context, raw json.RawMessage) (any, error) {
var info InitInfo
if err := json.Unmarshal(raw, &info); err != nil {
return nil, err
}
s.mu.Lock()
if info.Locale == "" {
info.Locale = "en-US"
}
s.initInfo = info
caps := s.caps
s.mu.Unlock()
return map[string]any{
"pluginApi": PluginAPIVersion,
"capabilities": caps,
}, nil
})
s.Handle("plugin/localeChanged", func(_ context.Context, raw json.RawMessage) (any, error) {
var ev LocaleChangedEvent
if err := json.Unmarshal(raw, &ev); err != nil {
return nil, nil
}
var bundleCopy map[string]string
if ev.L10nBundle != nil {
bundleCopy = make(map[string]string, len(ev.L10nBundle))
for k, v := range ev.L10nBundle {
bundleCopy[k] = v
}
}
s.mu.Lock()
if ev.Locale != "" {
s.initInfo.Locale = ev.Locale
}
if len(ev.FallbackChain) > 0 {
s.initInfo.FallbackChain = append([]string(nil), ev.FallbackChain...)
}
s.initInfo.L10nBundle = bundleCopy
cb := s.onLocaleChanged
s.mu.Unlock()
if cb != nil {
evCopy := ev
evCopy.FallbackChain = append([]string(nil), ev.FallbackChain...)
if bundleCopy != nil {
evCopy.L10nBundle = make(map[string]string, len(bundleCopy))
for k, v := range bundleCopy {
evCopy.L10nBundle[k] = v
}
}
cb(evCopy)
}
return nil, nil
})
return s
}
// OnLocaleChanged registers an optional callback invoked when the host broadcasts
// `plugin/localeChanged` at runtime.
func (s *Server) OnLocaleChanged(fn func(LocaleChangedEvent)) {
s.mu.Lock()
s.onLocaleChanged = fn
s.mu.Unlock()
}
// Locale returns the active effective BCP-47 locale negotiated with the host.
func (s *Server) Locale() string {
s.mu.Lock()
loc := s.initInfo.Locale
s.mu.Unlock()
if loc == "" {
return "en-US"
}
return loc
}
// FallbackChain returns the active locale fallback chain negotiated with the host.
func (s *Server) FallbackChain() []string {
s.mu.Lock()
defer s.mu.Unlock()
return append([]string(nil), s.initInfo.FallbackChain...)
}
// T formats a plugin-private localization key using the merged L10nBundle pushed
// by Reims-Go (combining the plugin's own `<l10n>/<tag>.json` with any active
// Language Pack `pluginOverrides`), substituting `{var}` placeholders from vars.
func (s *Server) T(key string, vars map[string]any) string {
s.mu.Lock()
tpl := ""
if s.initInfo.L10nBundle != nil {
tpl = s.initInfo.L10nBundle[key]
}
s.mu.Unlock()
if tpl == "" {
tpl = key
}
if !strings.ContainsRune(tpl, '{') && !strings.ContainsRune(tpl, '\'') {
return tpl
}
var b strings.Builder
b.Grow(len(tpl) + 16)
for i := 0; i < len(tpl); {
if tpl[i] == '\'' {
if i+1 < len(tpl) && tpl[i+1] == '\'' {
b.WriteByte('\'')
i += 2
continue
}
// ICU DOUBLE_OPTIONAL: only enter quoted span when ' precedes '{', '}', or '#'.
if i+1 < len(tpl) && (tpl[i+1] == '{' || tpl[i+1] == '}' || tpl[i+1] == '#') {
i++
for i < len(tpl) {
if tpl[i] == '\'' {
if i+1 < len(tpl) && tpl[i+1] == '\'' {
b.WriteByte('\'')
i += 2
continue
}
i++
break
}
b.WriteByte(tpl[i])
i++
}
continue
}
b.WriteByte('\'')
i++
continue
}
if tpl[i] == '{' && len(vars) > 0 {
// Scan matching brace depth so nested ICU plural/select blocks aren't truncated.
depth := 1
j := i + 1
for j < len(tpl) && depth > 0 {
if tpl[j] == '{' {
depth++
} else if tpl[j] == '}' {
depth--
}
j++
}
if depth == 0 {
inner := strings.TrimSpace(tpl[i+1 : j-1])
if inner != "" && !strings.ContainsAny(inner, "{}") {
token := inner
if comma := strings.IndexByte(token, ','); comma > 0 {
token = strings.TrimSpace(token[:comma])
}
if val, ok := vars[token]; ok && val != nil {
b.WriteString(fmt.Sprint(val))
i = j
continue
}
}
}
}
b.WriteByte(tpl[i])
i++
}
return b.String()
}
// SetCapability advertises a capability in the handshake response.
func (s *Server) SetCapability(k string, v any) {
s.mu.Lock()
s.caps[k] = v
s.mu.Unlock()
}
// InitInfo returns a defensive copy of the handshake metadata sent by the host.
func (s *Server) InitInfo() InitInfo {
s.mu.Lock()
defer s.mu.Unlock()
cp := s.initInfo
if len(s.initInfo.FallbackChain) > 0 {
cp.FallbackChain = append([]string(nil), s.initInfo.FallbackChain...)
}
if s.initInfo.L10nBundle != nil {
cp.L10nBundle = make(map[string]string, len(s.initInfo.L10nBundle))
for k, v := range s.initInfo.L10nBundle {
cp.L10nBundle[k] = v
}
}
return cp
}
// Handle registers a JSON-RPC method handler (e.g. "hook/vm.beforeStart",
// "command/invoke", "diagnostics/collect", "driver/list", ...).
func (s *Server) Handle(method string, h Handler) {
s.mu.Lock()
s.handlers[method] = h
s.mu.Unlock()
}
// CallHost invokes a reverse Host API method on Reims-Go (e.g. "host/notify",
// "host/vm.spawn", "host/vm.stop", "host/audit").
func (s *Server) CallHost(ctx context.Context, method string, params any, out any) error {
idStr := strconv.FormatUint(s.nextID.Add(1), 10)
var rawParams json.RawMessage
if params != nil {
b, err := json.Marshal(params)
if err != nil {
return err
}
rawParams = b
}
ch := make(chan envelope, 1)
s.mu.Lock()
s.pending[idStr] = ch
s.mu.Unlock()
defer func() {
s.mu.Lock()
delete(s.pending, idStr)
s.mu.Unlock()
}()
if err := s.writeFrame(envelope{
JSONRPC: "2.0",
ID: json.RawMessage(idStr),
Method: method,
Params: rawParams,
}); err != nil {
return err
}
select {
case resp := <-ch:
if resp.Error != nil {
return errors.New(resp.Error.Message)
}
if out != nil && len(resp.Result) > 0 && string(resp.Result) != "null" {
return json.Unmarshal(resp.Result, out)
}
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// SpawnVMProcess requests Reims-Go to spawn a VM process outside the Sidecar's Job Object.
func (s *Server) SpawnVMProcess(ctx context.Context, vmName, exePath string, args []string, workDir string, env []string) (int, error) {
var resp struct {
PID int `json:"pid"`
}
err := s.CallHost(ctx, "host/vm.spawn", map[string]any{
"vm_name": vmName,
"exe_path": exePath,
"args": args,
"work_dir": workDir,
"env": env,
}, &resp)
return resp.PID, err
}
// VMRef identifies a VM by its owning driver and name. Two drivers may own VMs
// with the same name, so a Sidecar with several drivers always sends the ref.
type VMRef struct {
DriverID string `json:"driver_id"`
Name string `json:"name"`
}
// GuestOSInfo describes the guest operating system (family is one of
// "macos", "linux", "windows", "android").
type GuestOSInfo struct {
Family string `json:"family,omitempty"`
Distro string `json:"distro,omitempty"`
Version string `json:"version,omitempty"`
Arch string `json:"arch,omitempty"`
}
// VMEndpoint is one way to reach a guest. Kind is one of "ssh", "wsl", "rdp",
// "vmconnect" and "adb"; the host runs a fixed command per kind.
type VMEndpoint struct {
Kind string `json:"kind"`
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
User string `json:"user,omitempty"`
Distro string `json:"distro,omitempty"`
VM string `json:"vm,omitempty"`
Serial string `json:"serial,omitempty"`
Ready bool `json:"ready"`
}
// VMStateReport is the payload of `host/vm.reportState`.
type VMStateReport struct {
Ref VMRef `json:"ref"`
State string `json:"state"`
Ready *bool `json:"ready,omitempty"`
Phase string `json:"phase,omitempty"`
Endpoints []VMEndpoint `json:"endpoints,omitempty"`
GuestOS *GuestOSInfo `json:"guest_os,omitempty"`
}
// SpawnVMProcessWithRef spawns a VM process owned by ref. The host puts the
// process and every child it starts into one per-VM job, so monitoring,
// affinity and window lookup cover the whole tree.
func (s *Server) SpawnVMProcessWithRef(ctx context.Context, ref VMRef, exePath string, args []string, workDir string, env []string) (int, error) {
var resp struct {
PID int `json:"pid"`
}
err := s.CallHost(ctx, "host/vm.spawn", map[string]any{
"ref": ref,
"vm_name": ref.Name,
"exe_path": exePath,
"args": args,
"work_dir": workDir,
"env": env,
}, &resp)
return resp.PID, err
}
// StopVMProcessByRef terminates every process of ref's VM job.
func (s *Server) StopVMProcessByRef(ctx context.Context, ref VMRef) error {
return s.CallHost(ctx, "host/vm.stop", map[string]any{"ref": ref}, nil)
}
// IsVMProcessRunningByRef reports whether ref's VM job still has a process.
func (s *Server) IsVMProcessRunningByRef(ctx context.Context, ref VMRef) (bool, error) {
var resp struct {
Running bool `json:"running"`
}
err := s.CallHost(ctx, "host/vm.isRunning", map[string]any{"ref": ref}, &resp)
return resp.Running, err
}
// ReportVMState pushes the state of a VM the driver owns to the host.
func (s *Server) ReportVMState(ctx context.Context, report VMStateReport) error {
return s.CallHost(ctx, "host/vm.reportState", report, nil)
}
// MaterializeSecretRequest asks the host to fill Template with a secret
// setting and write the result to Dest inside the VM's folder. Format is
// "raw" (default), "xml" or "base64-utf16le"; Template must hold {{secret}}.
type MaterializeSecretRequest struct {
Setting string `json:"setting"`
Ref VMRef `json:"ref"`
Template string `json:"template"`
Dest string `json:"dest"`
Format string `json:"format,omitempty"`
}
// MaterializeSecret has the host write a file containing a secret setting and
// returns its path. The plugin never sees the secret itself.
func (s *Server) MaterializeSecret(ctx context.Context, req MaterializeSecretRequest) (string, error) {
var resp struct {
Path string `json:"path"`
}
err := s.CallHost(ctx, "host/secret.materialize", req, &resp)
return resp.Path, err
}
// DownloadRequest asks the host to download URL to Dest. The plugin must
// declare a `net:` permission for the URL's origin (HTTPS, or HTTP for
// loopback). Dest is relative to the plugin's data folder, or an absolute path
// inside it or inside a VM root the plugin's driver declared. The host verifies
// every file, so SHA256 or SHA256URL (with SHA256Name selecting a line) is
// required.
type DownloadRequest struct {
URL string `json:"url"`
SHA256 string `json:"sha256,omitempty"`
SHA256URL string `json:"sha256_url,omitempty"`
SHA256Name string `json:"sha256_name,omitempty"`
Dest string `json:"dest"`
Size int64 `json:"size,omitempty"`
Label string `json:"label,omitempty"`
}
// DownloadEvent is the payload of the host's `download/progress` notification.
// Status is "running", "done", "failed" or "canceled".
type DownloadEvent struct {
ID string `json:"id"`
Status string `json:"status"`
Done int64 `json:"done"`
Total int64 `json:"total"`
Percent float64 `json:"percent"`
Path string `json:"path,omitempty"`
Error string `json:"error,omitempty"`
}
// StartDownload has the host download a file in the background, with progress
// in the host's task list. It returns the download ID that
// `download/progress` notifications carry.
func (s *Server) StartDownload(ctx context.Context, req DownloadRequest) (string, error) {
var resp struct {
ID string `json:"id"`
}
err := s.CallHost(ctx, "host/download.start", req, &resp)
return resp.ID, err
}
// CancelDownload stops one of this plugin's downloads.
func (s *Server) CancelDownload(ctx context.Context, id string) error {
return s.CallHost(ctx, "host/download.cancel", map[string]any{"id": id}, nil)
}
// ElevationResult is returned by `host/elevate.request` after the user
// confirms both the host dialog and the Windows UAC prompt.
type ElevationResult struct {
OK bool `json:"ok"`
Action string `json:"action"`
ExitCode int `json:"exit_code,omitempty"`
RebootRequired bool `json:"reboot_required,omitempty"`
LogoffRequired bool `json:"logoff_required,omitempty"`
}
// RequestElevation asks the host to run one whitelisted Windows elevation
// action (`hyperv.enable`, `hyperv.addAdminGroup`, or `sandbox.enable`)
// after explicit user confirmation in the desktop window and Windows UAC.
func (s *Server) RequestElevation(ctx context.Context, action string) (ElevationResult, error) {
var resp ElevationResult
err := s.CallHost(ctx, "host/elevate.request", map[string]any{"action": action}, &resp)
return resp, err
}
// DiscardSecret deletes the files the host materialized for ref's VM, or only
// path when it is set. It returns how many files were removed.
func (s *Server) DiscardSecret(ctx context.Context, ref VMRef, path string) (int, error) {
var resp struct {
Removed int `json:"removed"`
}
err := s.CallHost(ctx, "host/secret.discard", map[string]any{"ref": ref, "path": path}, &resp)
return resp.Removed, err
}
// StopVMProcess requests Reims-Go to terminate a host-managed VM process.
func (s *Server) StopVMProcess(ctx context.Context, pid int) error {
return s.CallHost(ctx, "host/vm.stop", map[string]any{"pid": pid}, nil)
}
// IsVMProcessRunning queries whether a host-managed VM process is still alive.
func (s *Server) IsVMProcessRunning(ctx context.Context, pid int) (bool, error) {
var resp struct {
Running bool `json:"running"`
}
err := s.CallHost(ctx, "host/vm.isRunning", map[string]any{"pid": pid}, &resp)
return resp.Running, err
}
// Notify requests a host UI notification (requires ui:notify permission).
func (s *Server) Notify(ctx context.Context, title, body string) error {
return s.CallHost(ctx, "host/notify", map[string]any{"title": title, "body": body}, nil)
}
// Serve runs the JSON-RPC frame loop until EOF or `plugin/shutdown`.
func (s *Server) Serve(ctx context.Context) error {
for {
if ctx.Err() != nil {
return ctx.Err()
}
frame, err := readFrame(s.in)
if err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
var env envelope
if err := json.Unmarshal(frame, &env); err != nil {
continue
}
if env.Method == "plugin/shutdown" {
return nil
}
if env.Method == "plugin/localeChanged" {
// Apply locale changes in arrival order to avoid stale overwrites.
s.dispatch(ctx, env)
continue
}
if env.Method != "" {
go s.dispatch(ctx, env)
continue
}
if len(env.ID) > 0 {
key := strings.TrimSpace(string(env.ID))
s.mu.Lock()
ch := s.pending[key]
s.mu.Unlock()
if ch != nil {
select {
case ch <- env:
default:
}
}
}
}
}
func (s *Server) dispatch(ctx context.Context, env envelope) {
s.mu.Lock()
h := s.handlers[env.Method]
s.mu.Unlock()
if h == nil {
if len(env.ID) > 0 {
_ = s.writeFrame(envelope{
JSONRPC: "2.0",
ID: env.ID,
Error: &rpcError{Code: -32601, Message: "method not found: " + env.Method},
})
}
return
}
res, err := h(ctx, env.Params)
if len(env.ID) == 0 {
return
}
if err != nil {
_ = s.writeFrame(envelope{
JSONRPC: "2.0",
ID: env.ID,
Error: &rpcError{Code: -32000, Message: err.Error()},
})
return
}
var rawRes json.RawMessage
if res == nil {
rawRes = json.RawMessage("null")
} else {
rawRes, _ = json.Marshal(res)
}
_ = s.writeFrame(envelope{
JSONRPC: "2.0",
ID: env.ID,
Result: rawRes,
})
}
func (s *Server) writeFrame(env envelope) error {
b, err := json.Marshal(env)
if err != nil {
return err
}
s.writeMu.Lock()
defer s.writeMu.Unlock()
if _, err := fmt.Fprintf(s.out, "Content-Length: %d\r\n\r\n", len(b)); err != nil {
return err
}
_, err = s.out.Write(b)
return err
}
func readFrame(r *bufio.Reader) ([]byte, error) {
contentLen := -1
for {
line, err := r.ReadString('\n')
if err != nil {
return nil, err
}
line = strings.TrimRight(line, "\r\n")
if line == "" {
break
}
k, v, ok := strings.Cut(line, ":")
if ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") {
n, err := strconv.Atoi(strings.TrimSpace(v))
if err != nil || n < 0 {
return nil, fmt.Errorf("invalid Content-Length %q", v)
}
contentLen = n
}
}
if contentLen < 0 {
return nil, errors.New("missing Content-Length")
}
buf := make([]byte, contentLen)
if _, err := io.ReadFull(r, buf); err != nil {
return nil, err
}
return buf, nil
}