Files
Reims-Go/pkg/pluginproto/types.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

409 lines
14 KiB
Go

package pluginproto
// The wire types of every host/* method. Both the host handlers and
// pkg/pluginsdk decode and encode these, so a field cannot exist on one side
// only.
// VMRef identifies a VM by owning driver and name. Two drivers may own VMs
// with the same name, so a caller that knows the driver always sends the ref.
type VMRef struct {
DriverID string `json:"driver_id"`
Name string `json:"name"`
}
// VMEndpoint is one way to reach a guest. Kind is one of "ssh", "wsl", "rdp",
// "vmconnect" and "adb".
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"`
}
// GuestOSInfo describes the guest operating system. Family is one of "macos",
// "linux", "windows" and "android".
type GuestOSInfo struct {
Family string `json:"family,omitempty"`
Distro string `json:"distro,omitempty"`
Version string `json:"version,omitempty"`
Arch string `json:"arch,omitempty"`
}
// ReportedVMState is the payload of host/vm.reportState.
type ReportedVMState 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"`
}
// OKResult is the result of the methods that only report success.
type OKResult struct {
OK bool `json:"ok"`
}
// NotifyParams is the payload of host/notify.
type NotifyParams struct {
Title string `json:"title"`
Body string `json:"body"`
}
// AuditParams is the payload of host/audit.
type AuditParams struct {
Message string `json:"message"`
}
// SpawnParams is the payload of host/vm.spawn. Ref wins over vm_name when both
// are set.
type SpawnParams struct {
VMName string `json:"vm_name,omitempty"`
Ref *VMRef `json:"ref,omitempty"`
ExePath string `json:"exe_path"`
Args []string `json:"args,omitempty"`
WorkDir string `json:"work_dir,omitempty"`
Env []string `json:"env,omitempty"`
}
// SpawnResult is the result of host/vm.spawn.
type SpawnResult struct {
PID int `json:"pid"`
}
// ProcessParams addresses a process by pid or by the VM ref whose job object
// holds it. It is the payload of host/vm.stop and host/vm.isRunning.
type ProcessParams struct {
PID int `json:"pid,omitempty"`
Ref *VMRef `json:"ref,omitempty"`
}
// IsRunningResult is the result of host/vm.isRunning.
type IsRunningResult struct {
Running bool `json:"running"`
}
// DownloadParams is the payload of host/download.start. SHA256 or SHA256URL
// (with SHA256Name selecting a line) is required; the host verifies the file.
type DownloadParams 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"`
ConnectTimeoutMS int `json:"connect_timeout_ms,omitempty"`
StallTimeoutMS int `json:"stall_timeout_ms,omitempty"`
AllowCustomMirror bool `json:"allow_custom_mirror,omitempty"`
}
// DownloadResult is the result of host/download.start.
type DownloadResult struct {
ID string `json:"id"`
TaskID string `json:"task_id"`
}
// DownloadCancelParams is the payload of host/download.cancel.
type DownloadCancelParams struct {
ID string `json:"id"`
}
// SecretMaterializeParams is the payload of host/secret.materialize. Template
// must hold {{secret}}; Format is "raw" (default), "xml" or "base64-utf16le".
type SecretMaterializeParams struct {
Setting string `json:"setting"`
Ref VMRef `json:"ref"`
Template string `json:"template"`
Dest string `json:"dest"`
Format string `json:"format,omitempty"`
}
// SecretMaterializeResult is the result of host/secret.materialize.
type SecretMaterializeResult struct {
Path string `json:"path"`
}
// SecretDiscardParams is the payload of host/secret.discard. An empty Path
// discards every file the host materialized for Ref.
type SecretDiscardParams struct {
Ref VMRef `json:"ref"`
Path string `json:"path,omitempty"`
}
// SecretDiscardResult is the result of host/secret.discard.
type SecretDiscardResult struct {
Removed int `json:"removed"`
}
// ElevateParams is the payload of host/elevate.request.
type ElevateParams struct {
Action string `json:"action"`
}
// ElevateResult is the result of host/elevate.request, after the user
// confirmed both the host dialog and the Windows UAC prompt.
type ElevateResult 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"`
}
// VMParams addresses one VM by name or by canonical driverID:name reference.
type VMParams struct {
VM string `json:"vm"`
}
// VMShutdownParams is the payload of host/vm.shutdown. Force stops a VM that
// does not shut down on request.
type VMShutdownParams struct {
VM string `json:"vm"`
Force bool `json:"force,omitempty"`
}
// VMRestartParams is the payload of host/vm.restart.
type VMRestartParams struct {
VM string `json:"vm"`
GracefulTimeoutSec int `json:"graceful_timeout_sec,omitempty"`
}
// VMView is what host/vm.list and host/vm.get report about one VM. Fields
// that need the user's per-VM consent are present only when it was granted.
type VMView struct {
VM string `json:"vm"`
Name string `json:"name"`
DriverID string `json:"driver_id"`
State string `json:"state"`
Authorized bool `json:"authorized"`
Phase string `json:"phase"`
Owned bool `json:"owned"`
CPUs int `json:"cpus,omitempty"`
Memory string `json:"memory,omitempty"`
DiskSummary string `json:"disk_summary,omitempty"`
SSHPort int `json:"ssh_port,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
SSHUsername string `json:"ssh_username,omitempty"`
}
// VMListResult is the result of host/vm.list.
type VMListResult struct {
VMs []VMView `json:"vms"`
}
// VMCloneParams is the payload of host/vm.clone. The host registers the clone
// as this plugin's temporary VM, so a plugin may name it freely; the name only
// has to be free on the source VM's driver.
type VMCloneParams struct {
VM string `json:"vm"`
CloneName string `json:"clone_name"`
}
// VMCloneResult is the result of host/vm.clone.
type VMCloneResult struct {
VM string `json:"vm"`
Name string `json:"name"`
DriverID string `json:"driver_id"`
State string `json:"state"`
Owned bool `json:"owned"`
}
// SnapshotNameParams is the payload of host/vm.snapshot.create and
// host/vm.snapshot.restore.
type SnapshotNameParams struct {
VM string `json:"vm"`
Name string `json:"name"`
}
// Snapshot describes one restore point.
type Snapshot struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedAt int64 `json:"created_at"`
VMStateBytes int64 `json:"vm_state_bytes"`
}
// SnapshotListResult is the result of host/vm.snapshot.list.
type SnapshotListResult struct {
Snapshots []Snapshot `json:"snapshots"`
}
// SnapshotResult is the result of host/vm.snapshot.create and
// host/vm.snapshot.restore.
type SnapshotResult struct {
OK bool `json:"ok"`
Name string `json:"name"`
}
// Region is a rectangle. In a screenshot request it is expressed in the
// coordinate space of the reference frame the caller sends as Width and
// Height; in a screenshot result it is the source-pixel rectangle that was
// captured.
type Region struct {
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
}
// ScreenshotParams is the payload of host/console.screenshot. MaxWidth caps
// the width of the returned image; a value outside the supported range is
// brought into it rather than refused. Region selects a part of the screen:
// Width and Height name the image the region was measured in, and without them
// the region is in source pixels.
type ScreenshotParams struct {
VM string `json:"vm"`
MaxWidth int `json:"max_width,omitempty"`
MaxEdge *int `json:"max_edge,omitempty"`
Format string `json:"format,omitempty"`
Region *Region `json:"region,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
}
// ScreenshotResult is the result of host/console.screenshot. Blank marks a
// frame that is one flat color, which is a normal state during boot, login and
// display switches rather than a failure.
type ScreenshotResult struct {
MIMEType string `json:"mime_type"`
Width int `json:"width"`
Height int `json:"height"`
SourceWidth int `json:"source_width"`
SourceHeight int `json:"source_height"`
Blank bool `json:"blank"`
Data string `json:"data"`
Region *Region `json:"region,omitempty"`
}
// PointerParams is the payload of host/console.pointer. Action is one of
// "move", "button", "click" and "scroll". Move and button down/up leave the
// guest holding what was pressed until a later call releases it.
type PointerParams struct {
VM string `json:"vm"`
Action string `json:"action"`
X int `json:"x,omitempty"`
Y int `json:"y,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Button string `json:"button,omitempty"`
Down *bool `json:"down,omitempty"`
Delta int `json:"delta,omitempty"`
Horizontal bool `json:"horizontal,omitempty"`
}
// KeyParams is the payload of host/console.key. Without Down the host presses
// and releases Key with Modifiers held. With Down set the host sends key
// transitions for Key and every modifier and the guest keeps them held until a
// later call releases them, so the caller must pair it or call
// host/console.release.
type KeyParams struct {
VM string `json:"vm"`
Key string `json:"key"`
Modifiers []string `json:"modifiers,omitempty"`
Down *bool `json:"down,omitempty"`
}
// TypeParams is the payload of host/console.type.
type TypeParams struct {
VM string `json:"vm"`
Text string `json:"text"`
}
// TypeSecretParams is the payload of host/console.typeSecret. Setting names one
// of the calling plugin's own settings; the host never returns its value, so a
// plugin can use a secret it stored without ever reading it.
type TypeSecretParams struct {
VM string `json:"vm"`
Setting string `json:"setting"`
}
// ReleaseParams is the payload of host/console.release. It lifts the keys and
// pointer buttons the caller still holds in the guest.
type ReleaseParams struct {
VM string `json:"vm"`
Keys []string `json:"keys,omitempty"`
Buttons []string `json:"buttons,omitempty"`
}
// CharactersResult is the result of host/console.type and
// host/console.typeSecret.
type CharactersResult struct {
Characters int `json:"characters"`
}
// ConfirmParams is the payload of host/ui.confirm.
type ConfirmParams struct {
Title string `json:"title"`
Message string `json:"message"`
ConfirmLabel string `json:"confirm_label,omitempty"`
CancelLabel string `json:"cancel_label,omitempty"`
Danger bool `json:"danger,omitempty"`
VM string `json:"vm,omitempty"`
ProtectedPhase string `json:"protected_phase,omitempty"`
AllowDurationChoice bool `json:"allow_duration_choice,omitempty"`
DefaultDurationMin int `json:"default_duration_minutes,omitempty"`
PreferUntilPhaseExit bool `json:"prefer_until_phase_exit,omitempty"`
}
// ConfirmResult is the result of host/ui.confirm.
type ConfirmResult struct {
Approved bool `json:"approved"`
DurationMinutes int `json:"duration_minutes,omitempty"`
UntilPhaseExit bool `json:"until_phase_exit,omitempty"`
Reason string `json:"reason,omitempty"`
}
// SessionBeginParams is the payload of host/session.begin.
type SessionBeginParams struct {
VM string `json:"vm"`
Label string `json:"label,omitempty"`
Stage string `json:"stage,omitempty"`
TakeoverPolicy string `json:"takeover_policy,omitempty"`
RequestProtectedPhaseAuth bool `json:"request_protected_phase_auth,omitempty"`
PreferUntilPhaseExit bool `json:"prefer_until_phase_exit,omitempty"`
}
// SessionUpdateParams is the payload of host/session.update.
type SessionUpdateParams struct {
VM string `json:"vm"`
Stage string `json:"stage,omitempty"`
Step string `json:"step,omitempty"`
Status string `json:"status,omitempty"`
Message string `json:"message,omitempty"`
PausedForUser *bool `json:"paused_for_user,omitempty"`
}
// SessionEndParams is the payload of host/session.end.
type SessionEndParams struct {
VM string `json:"vm"`
Status string `json:"status,omitempty"`
Message string `json:"message,omitempty"`
}
// TelemetryMilestone is one parsed boot/runtime milestone reported by host/vm.telemetry.
type TelemetryMilestone struct {
Key string `json:"key"`
Count int `json:"count"`
At string `json:"at"`
}
// VMTelemetryResult is the result of host/vm.telemetry.
type VMTelemetryResult struct {
VM string `json:"vm"`
State string `json:"state"`
Phase string `json:"phase"`
PID int `json:"pid"`
BootMilestones []TelemetryMilestone `json:"boot_milestones,omitempty"`
QemuErrors []string `json:"qemu_errors,omitempty"`
DiskBytes int64 `json:"disk_bytes"`
DiskDeltaBytes int64 `json:"disk_delta_bytes"`
CPUPercent float64 `json:"cpu_percent"`
ColdRebootCount int `json:"cold_reboot_count"`
UpdatedAt string `json:"updated_at,omitempty"`
}