Files
Reims-Go/pkg/pluginproto/proto.go
T
球球 7fd1947bef feat(plugin,host,macos,ui): 实现 Agent 受控接管、受保护阶段确认、离线预配置与自动装机基础 (#103, #105, #129) (#134)
* feat(plugin,host,ui): add agent session takeover, protected-phase confirmation, and autoinstall host foundation

* feat(macos,ui,cli): add offline REIMSPROV first-boot provisioning to skip Setup Assistant (#129)

Builds a per-VM read-only REIMSPROV disk image containing a pure-Go XAR Distribution flat package (provision.pkg) and an offline Recovery fallback script (provision-offline.sh). Passwords are hashed in memory to Apple SALTED-SHA512-PBKDF2 bplist00 ShadowHashData (never persisted in plaintext, no auto-login or NOPASSWD sudo). Uses native OpenDirectory.framework (JXA NSData) + dseditgroup under SIP-enabled live bootinstalld and dslocal plist + PlistBuddy under offline Recovery, skips Setup Assistant and Keyboard Setup Assistant, pre-stages Guest Tools, integrates with CreateWizard / VMPage / vm provision CLI / StartAutoInstall, and zero-wipes on finish_install, normal cold start, or DeleteVM.

* feat(autoinstall,host,ui): add input-locked session shield, recovery-only mode, and restart grace cap

Adds the real-machine end-to-end verified baseline for automatic macOS installation: (1) takeover_policy 'lock' with transparent Win32 VM client-area input shield, low-level key/mouse lock preserving host escape shortcuts (Alt+Tab/Alt+Esc/Win), HUD & UI Pause/Resume controls, and write guards while paused; (2) decoupled recovery_only vs full (REIMSPROV) modes in StartAutoInstall, CreateWizard, and VMAutoInstallPanel; (3) graceful_timeout_sec cap (default 10s) on automated built-in macOS host/vm.restart so Setup Assistant/Login Window restarts do not stall 90s on ACPI; (4) additional modifier aliases in console manager and agent-session/telemetry cleanup on VM deletion.

* feat(autoinstall,overlay,plugin): add built-in macOS auto-install plugin, dynamic island overlay, and review fixes

* fix(app,host,macos,ui): address PR #134 automated review findings

- Frontend & i18n:
  - Fix UTF-8/GBK mojibake in VMPage.tsx.
  - Emit reims:confirm-resolved on timeout/cancel/resolve so frontend modals auto-close and surface errors cleanly; stop submitCreate from continuing after PrepareVMProvision failure.
  - Gate AutoInstallPanel RapidOCR download button on preflight can_download_ocr when pinned default assets are unavailable.
- App / Sessions / Confirm / Lifecycle:
  - Add 30s denial cooldown for protected-phase confirmation prompts and revoke (pluginID, vmKey) grants on non-completed session exits.
  - Fix sessionOverlay / activeAgentSessions data race, remove duplicate permission-denied invocation, guard against clobbering other sessions or completed overlays, and unify VM key normalization.
  - Grant protected-phase confirmation and attach lock-mode session + watcher when resuming auto-install without an active session.
  - Unify FinishInstall and host/vm.finishInstall result handling and persist .reims-go-provision-ready across restarts.
  - Preserve non-timeout stop errors in restartMacOSVMLocked instead of force-killing.
- Host Takeover Hooks:
  - Require both keyboard and mouse WH_*_LL hooks (rolling back partial installs), initialize thread message queue before ready, reset started state on error/exit for retry, and report hook failures.
- macOS Provisioning & Autoinstall Engine:
  - Track REIMSPROV staged/wipe-pending/ready lifecycle markers, exclude "restore" recovery marker from re-attaching REIMSPROV, fail explicitly on offline admin plist creation failure, and report wipe failures.
  - Serialize per-VM Start/Stop/Resume with stop generation tokens, guard ROI fast-path against maxDim overflow, switch hostclient early-event buffer to FIFO eviction, fix untyped nil Engine return, tighten negation & high-risk fuzzy matching, preserve ackedQemuErrors across RebootWindow resets, and re-orient/expire stale inherited running checkpoints.
  - Document verified Windows SDK IDL vtable slots for WinOCR (live-tested on Windows) and add regression tests across app, host, macosdriver, startprep, installer, and autoinstall packages.

* fix(app,cli,host,macos,ui): address PR #134 second automated review findings

- CLI & Desktop Control Channel:
  - Add __reims_host__ / autoinstall desktop control channel with data_root verification so CLI status, resume, and stop talk directly to the live desktop runner instead of splitting checkpoint state or launching doomed short-lived CLI runners.
  - Merge live runners with on-disk checkpoints when listing status without a VM argument.
- App Sessions, Confirmations, Downloads & Telemetry:
  - Scope single-VM not_authorized errors to the target VM in handleSessionBegin and resolveComputerUseVM so active sessions on other VMs are not aborted.
  - Exclude stopped and suspended VMs from hasUnboundAgentSession fast-polling.
  - Revoke protected-phase grants when a VM disappears from poll results.
  - Require manifest Secret:true validation before storing auto-install passwords and remove the unsafe default account_password fallback.
  - Reject userinfo URLs in allow_custom_mirror, gate custom-mirror exemption strictly on plugin.ErrNetOriginNotDeclared, and keep redirect SSRF checks enabled on loopback custom mirrors.
  - Preserve VM telemetry milestones across suspend-resume and Win10 cold-reboot restarts while still resetting on fresh cold boots.
  - Log a warning when Guest Tools bridge is unavailable while preparing REIMSPROV.
  - Clarify CallHostAPI authorization/audit contract and add regression test proving built-in plugins enforce catalog permissions and audit logging.
- Host Takeover & Guest Tools:
  - Track locked mouse button presses via a 5-button bitmask so ButtonUp events from drags started outside the VM window are never swallowed.
  - Align active-window-reporter.js permissions to 0o100755 across ToolsDiskFiles, ToolsProvisionFiles, and postinstall.
- macOS Provisioning & Autoinstall Engine (OCR / Vision / Rules / Runner):
  - Never delete an unwiped REIMSPROV image on OpenFile/Write/Sync failure; persist wipe-pending marker and return error for retry.
  - Harden live postinstall preference writes with chmod 600, plutil -lint, chown, and cfprefsd flush.
  - Rewrite Windows RapidOCR C ABI structs and result extraction to match RapidAI/RapidOcrOnnx@675e73fe4c include/OcrLiteCApi.h:27-70 and src/OcrLiteCApi.cpp:12-160 (5-arg OcrInit verified).
  - Inspect PE32/PE32+ IMAGE_DIRECTORY_ENTRY_IMPORT directly to require onnxruntime.dll only for dynamically linked RapidOcrOnnx.dll builds.
  - Validate cfg.VM and use collision-free SHA-256-suffixed checkpoint paths with read fallback; redact PII/paths/UUIDs/MACs/IPs/tokens in diagnostic summaries; snapshot checkpoints before releasing r.mu for serialized disk I/O.
  - Add contrast/border/focus-ring ok return to DetectInputFieldNearLabel, enforce mask-dots verification in fillAccountForm and login screens, refuse blind password typing on clock-only lock screens, confirm shell readiness before typing install.sh, and prefer isolated button lines over modal prose in FindHit.
- Frontend:
  - Require explicit Apple SLA confirmation in both recovery_only and full modes across AutoInstallPanel and CreateWizard, with unit tests in frontend/scripts/test-autoinstall.mjs.

* fix(app,cli,host,macos,ui): address PR #134 third automated review findings

Addresses all confirmed findings from Review #6204465334 (commit d516350)
with targeted regression tests and hardens verified COM vtable bindings:

- App & Session Lifecycle:
  - Track hostPaused separately in agentSession so plugin host/session.update
    (paused_for_user=false) cannot clear physical user takeover or explicit
    PauseAgentSession holds; only host ResumeAgentSession or timed takeover
    expiry clears them.
  - Give each auto-install session watcher a monotonic watchGen + cancelable
    child context so restarting/resuming auto-install on the same VM cancels
    any superseded watcher and prevents stale timeout or secret cleanup.
  - Bound fast 500ms unbound-PID discovery for running VMs to
    sessionDiscoverGraceWindow via unboundSince (refreshed on restart/rebind).
  - Keep non-blocking buffered confirm resolution send inside confirmMu for
    clear mutual exclusion with cancelPendingConfirmations.
  - Clear cold-reboot telemetry preserveNextBoot via defer on all early-return
    and StartVM-failure paths in watchColdReboot.
  - Rebuild REIMSPROV with current StartAutoInstall credentials (preserving
    install_guest_tools) whenever VM is stopped instead of reusing stale images.
- CLI & macOS Provisioning / StartPrep:
  - Refuse `vm provision --clear` and overwriting existing REIMSPROV while the
    VM is running or paused.
  - Guard live "/" root in postinstall against macOS Recovery/Installer
    (/System/Installation/CDIS), forbid "/" in provision-offline.sh, and scope
    chmod 644 strictly to com.apple.keyboardtype.plist.
  - Reject unknown -* options in REIMSHELP/install.sh (including after --erase).
  - Defer clearing the one-shot REIMSPROV staged marker until after
    setExtraArgs (startprep) and StartWithCompat (macosdriver) succeed.
  - Preserve pending RestartFrom guards in AdvancePostInstallHandoff when
    checkpoint is already at StepDesktop.
- Host Input & Session Overlay:
  - Filter injected keyboard events (LLKHF_INJECTED / LLKHF_LOWER_IL_INJECTED)
    in locked-input mode consistently with the mouse hook.
  - Clean up exited overlay entries in entry.run() and recreate dead entries on
    Manager.Upsert when CreateWindowExW fails or exits early.
  - Cache the static island base surface (shell + icons + DirectWrite text) and
    measured text metrics across breathing frames, raising timerBreathMs to 100ms.
  - Replace magic Direct2D/DirectWrite vtable indices with named d2d1.h /
    dwrite.h constants, check EndDraw HRESULT, and add a live Windows DirectWrite
    rendering smoke test.
- Autoinstall OCR, Rules, Watchdog & Runner:
  - Persist and verify a per-file SHA-256 manifest.json in <dataDir>/ocr/
    before loading RapidOcrOnnx.dll / onnxruntime.dll; reject duplicate
    whitelisted basenames in offline zip imports.
  - Signal WinOCREngine.Close() before acquiring e.mu and add bounded wait +
    channel wakeup in Recognize so Close() immediately cancels in-flight OCR.
  - Fall back to installed RapidOCR when WinOCR initialization fails in Open(),
    and distinguish needs_rapidocr_import from needs_rapidocr_download in Probe.
  - Pause instead of pressing Return when post-TypeSecret login screenshot fails.
  - Re-baseline ColdRebootCount in Watchdog.ResetRebootWindow / ResetAfterResume.
  - Tighten recovery.main specificity (drop bare "Disk Utility"), guard 4-5 char
    pure-ASCII needles from sliding-window fuzzy collisions, use Unicode word
    boundaries for short names (<4 runes) in RedactDiagnosticText, and honor
    rule verify.wait_change_ms with early exit on visual frame diff.

* fix(autoinstall): handle CJK short-name redaction, sh-3.2 prompt bound, and OCR re-import pruning
2026-12-06 15:46:39 +08:00

286 lines
11 KiB
Go

// Package pluginproto is the single source of truth for the Sidecar Host API:
// which host/* methods exist, which permissions each one needs, and the request
// and result shapes both sides decode. It imports only the standard library, so
// the host, pkg/pluginsdk and third-party plugins share one copy of the wire
// contract instead of each declaring its own anonymous structs.
//
// A method that is not in HostMethods is not part of the contract: the host
// answers it with JSON-RPC -32601, and a plugin must not call it.
package pluginproto
import (
"bytes"
"encoding/json"
"errors"
"io"
"sort"
"strings"
)
// Status marks whether the host acts on a method.
type Status string
const (
// StatusStable methods are implemented by the host and covered by the
// compatibility promise.
StatusStable Status = "stable"
// StatusExperimental methods are published so plugins can feature-detect
// them, but carry no compatibility promise.
StatusExperimental Status = "experimental"
)
// OriginPermission marks a method whose authorization depends on the request
// URL: the caller must declare net:<origin> for the URL it passes.
const OriginPermission = "net:<origin>"
// StrictParamsVersion is the pluginApi version from which a plugin's requests
// are decoded strictly. Older plugins keep tolerant decoding so a released
// plugin that sends a field this host has not implemented yet keeps working.
const StrictParamsVersion = "1.3.0"
// MethodSpec describes one host/* method.
type MethodSpec struct {
Status Status
// Permissions lists every permission the caller must hold. An empty list
// means the method needs none beyond being a registered plugin.
Permissions []string
// Feature is the handshake feature that advertises the method. An empty
// value derives one from the method name.
Feature string
// StrictParams makes the host reject request fields the contract does not
// define (JSON-RPC -32602) instead of ignoring them.
StrictParams bool
// Summary is one line for `plugin doctor` and the generated reference.
Summary string
}
// HostMethods is the authoritative catalog of reverse Host API methods.
var HostMethods = map[string]MethodSpec{
"host/notify": {
Status: StatusStable, Permissions: []string{"ui:notify"},
Summary: "Show a host notification.",
},
"host/audit": {
Status: StatusStable,
Summary: "Append one line to the plugin's audit log (rate limited).",
},
"host/vm.spawn": {
Status: StatusStable, Permissions: []string{"process:spawn"}, Feature: "host.vm.spawn.ref",
Summary: "Start a process for a VM and put it into that VM's job object.",
},
"host/vm.stop": {
Status: StatusStable, Permissions: []string{"vm:control"},
Summary: "Terminate a process this plugin started, by pid or by VM ref.",
},
"host/vm.isRunning": {
Status: StatusStable,
Summary: "Report whether a process this plugin started is still alive.",
},
"host/vm.reportState": {
Status: StatusStable, Permissions: []string{"driver:vm"}, Feature: "host.vm.reportState",
Summary: "Push the state of a VM the calling driver owns.",
},
"host/download.start": {
Status: StatusStable, Permissions: []string{OriginPermission}, Feature: "host.download",
Summary: "Download a checksum-verified file in the background.",
},
"host/download.cancel": {
Status: StatusStable, Feature: "host.download",
Summary: "Cancel one of this plugin's downloads.",
},
"host/secret.materialize": {
Status: StatusStable, Permissions: []string{"driver:vm", "fs:vm_dir"}, Feature: "host.secret.materialize",
Summary: "Have the host write one secret setting into a VM folder without revealing it.",
},
"host/secret.discard": {
Status: StatusStable, Permissions: []string{"driver:vm"}, Feature: "host.secret.materialize",
Summary: "Delete the secret files the host materialized for a VM.",
},
"host/elevate.request": {
Status: StatusStable, Permissions: []string{"driver:vm"}, Feature: "host.elevate.request",
Summary: "Ask the user to confirm one whitelisted Windows elevation action.",
},
"host/ui.confirm": {
Status: StatusStable, Permissions: []string{"ui:notify"}, Feature: "host.ui.confirm", StrictParams: true,
Summary: "Ask the user to confirm a host action or protected-phase authorization.",
},
"host/session.begin": {
Status: StatusStable, Permissions: []string{"qmp:write"}, Feature: "host.session", StrictParams: true,
Summary: "Begin a visible remote-control session on an authorized VM.",
},
"host/session.update": {
Status: StatusStable, Permissions: []string{"qmp:write"}, Feature: "host.session", StrictParams: true,
Summary: "Update the visible stage, status or pause state of an active session.",
},
"host/session.end": {
Status: StatusStable, Permissions: []string{"qmp:write"}, Feature: "host.session", StrictParams: true,
Summary: "End an active remote-control session on a VM.",
},
"host/vm.list": {
Status: StatusStable, Permissions: []string{"vm:read"}, StrictParams: true,
Summary: "List the VMs this plugin may see.",
},
"host/vm.get": {
Status: StatusStable, Permissions: []string{"vm:read"}, StrictParams: true,
Summary: "Read one VM's details.",
},
"host/vm.start": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Start a VM.",
},
"host/vm.shutdown": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Shut a VM down, or stop it outright when force is set.",
},
"host/vm.suspend": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Suspend a VM.",
},
"host/vm.resume": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Resume a VM.",
},
"host/vm.clone": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Clone a VM into a temporary VM this plugin owns.",
},
"host/vm.delete": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Delete a temporary VM this plugin owns.",
},
"host/vm.snapshot.list": {
Status: StatusStable, Permissions: []string{"vm:read"}, StrictParams: true,
Summary: "List a VM's snapshots.",
},
"host/vm.snapshot.create": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Create a snapshot.",
},
"host/vm.snapshot.restore": {
Status: StatusStable, Permissions: []string{"vm:control"}, StrictParams: true,
Summary: "Restore a snapshot of a VM the user authorized this plugin to access.",
},
"host/vm.finishInstall": {
Status: StatusStable, Permissions: []string{"vm:control"}, Feature: "host.vm.finishInstall", StrictParams: true,
Summary: "Invoke a VM driver's finish_install action to exit recovery/installer mode.",
},
"host/vm.restart": {
Status: StatusStable, Permissions: []string{"vm:control"}, Feature: "host.vm.restart", StrictParams: true,
Summary: "Stop a VM, wait for process exit, and start it again.",
},
"host/vm.telemetry": {
Status: StatusStable, Permissions: []string{"vm:read", "log:read"}, Feature: "host.vm.telemetry", StrictParams: true,
Summary: "Read structured, redacted runtime telemetry for an authorized VM.",
},
"host/console.screenshot": {
Status: StatusStable, Permissions: []string{"vm:screen"}, StrictParams: true,
Summary: "Capture the guest screen, optionally one region of it, as JPEG or PNG.",
},
"host/console.pointer": {
Status: StatusStable, Permissions: []string{"qmp:write"}, StrictParams: true,
Summary: "Move the pointer, press or release a button, click or scroll.",
},
"host/console.key": {
Status: StatusStable, Permissions: []string{"qmp:write"}, StrictParams: true,
Summary: "Press a key, or hold and release it with down.",
},
"host/console.type": {
Status: StatusStable, Permissions: []string{"qmp:write"}, StrictParams: true,
Summary: "Type text as US-layout key strokes.",
},
"host/console.typeSecret": {
Status: StatusStable, Permissions: []string{"qmp:write"}, StrictParams: true,
Summary: "Type one of this plugin's own secret settings without revealing it.",
},
"host/console.release": {
Status: StatusStable, Permissions: []string{"qmp:write"}, StrictParams: true,
Summary: "Release the keys and pointer buttons this plugin still holds.",
},
}
// Lookup returns the spec of one method.
func Lookup(method string) (MethodSpec, bool) {
spec, ok := HostMethods[method]
return spec, ok
}
// Methods lists every catalogued method, sorted.
func Methods() []string {
out := make([]string, 0, len(HostMethods))
for method := range HostMethods {
out = append(out, method)
}
sort.Strings(out)
return out
}
// Feature returns the handshake feature that advertises method.
func Feature(method string) string {
if spec, ok := HostMethods[method]; ok && spec.Feature != "" {
return spec.Feature
}
return "host." + strings.ReplaceAll(strings.TrimPrefix(method, "host/"), "/", ".")
}
// Features lists the handshake features of every stable method, sorted and
// without duplicates. Plugins feature-detect with these instead of comparing
// version numbers.
func Features() []string {
seen := map[string]bool{}
out := []string{}
for method, spec := range HostMethods {
if spec.Status != StatusStable {
continue
}
feature := Feature(method)
if seen[feature] {
continue
}
seen[feature] = true
out = append(out, feature)
}
sort.Strings(out)
return out
}
// InvalidParamsError reports a request the contract does not accept. The host
// answers it with JSON-RPC -32602.
type InvalidParamsError struct {
Method string
Reason string
}
func (e *InvalidParamsError) Error() string {
if e.Method == "" {
return e.Reason
}
return e.Method + ": " + e.Reason
}
// DecodeParams decodes one request into out. An absent or null params member
// leaves out at its zero value. With strict set, a field the contract does not
// define, or trailing data after the request object, is an error instead of
// being dropped silently.
func DecodeParams[T any](method string, raw json.RawMessage, strict bool) (T, error) {
var out T
trimmed := bytes.TrimSpace(raw)
if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
return out, nil
}
if !strict {
if err := json.Unmarshal(trimmed, &out); err != nil {
return out, &InvalidParamsError{Method: method, Reason: err.Error()}
}
return out, nil
}
dec := json.NewDecoder(bytes.NewReader(trimmed))
dec.DisallowUnknownFields()
if err := dec.Decode(&out); err != nil {
return out, &InvalidParamsError{Method: method, Reason: err.Error()}
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return out, &InvalidParamsError{Method: method, Reason: "unexpected data after the request object"}
}
return out, nil
}