Files
Reims-Go/internal/macos/startprep/startprep.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

309 lines
11 KiB
Go

// Package startprep runs macOS VM pre-launch checks and OpenCore/disk
// preparation shared by the desktop window and direct CLI launches.
package startprep
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/installer"
"github.com/Nwflower/reims-go/internal/macos/opencore"
"github.com/Nwflower/reims-go/internal/macos/reims"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// Prep runs start preparation against the active runtime. Log receives one
// human-readable line per step; the GUI routes it to the VM's log panel, the
// CLI to stderr.
type Prep struct {
Client *reims.Client
Runtime rt.Installed
// SkipWHPXFallback mirrors the whpx_fallback setting on builtin.guest.macos being off.
SkipWHPXFallback bool
cfg config.Config
log func(string)
}
// New resolves the active runtime for cfg. It fails when none is installed.
func New(cfg config.Config, log func(string)) (*Prep, error) {
active, err := rt.ResolveActive(&cfg)
if err != nil || active == nil {
return nil, fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
}
if log == nil {
log = func(string) {}
}
return &Prep{Client: reims.NewClient(&cfg, *active), Runtime: *active, cfg: cfg, log: log}, nil
}
// CheckWHPX refuses to start a VM when Windows Hypervisor Platform is not
// ready. Without it QEMU aborts with "WHPX: No accelerator found, hr=00000000"
// followed by "failed to initialize whpx: No space left on device" (-ENOSPC),
// which misleads users into checking disk space.
func (p *Prep) CheckWHPX(rep host.Report) error {
switch rep.WHPX {
case host.WHPXReady:
return nil
case host.WHPXMissing:
return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_missing"))
case host.WHPXHypervisorOff:
return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_hypervisor_off"))
case host.WHPXNoHypervisor:
return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_no_hypervisor"))
default:
return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.whpx_unsupported"))
}
}
// CheckMemory refuses to start a VM whose guest RAM cannot be committed right
// now, avoiding QEMU's opaque "Cannot set up guest memory 'ram'" exit.
func (p *Prep) CheckMemory(memory string, rep host.Report) error {
avail, ok := host.CommitAvailGB()
if !ok {
return nil
}
memGB, ok := reims.ParseSizeGB(memory)
if !ok || memGB+host.StartMarginGB <= avail {
return nil
}
return fmt.Errorf("%s", i18n.T(p.cfg.Locale, "err.commit_memory", memGB+host.StartMarginGB, memGB, avail, host.RecommendedMemoryGB(rep)))
}
// Prepare brings a stopped VM's configuration up to date before it starts:
// the offline-install helper disk, the recovery boot picker, the macOS
// language preset and the WHPX nested-virtualization fallback. cur is updated
// to match what was written through `reims-ctl set`.
func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) {
if stripped := reims.StripIncomingDeferArgs(cur.ExtraArgs); stripped != cur.ExtraArgs {
if err := p.setExtraArgs(ctx, name, stripped); err == nil {
cur.ExtraArgs = stripped
}
}
p.syncOfflineHelper(ctx, name, cur)
p.syncRecoveryBootPicker(ctx, name, cur)
p.ReplayGuestLang(ctx, cur.Directory)
if !p.SkipWHPXFallback {
p.applyProbedWHPXCompat(ctx, name, rep, cur)
}
p.syncHostMemorySMBIOS(ctx, name, rep, cur)
}
func (p *Prep) syncHostMemorySMBIOS(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) {
if rep.MemorySpec == nil || rep.MemorySpec.SpeedMHz <= 0 {
return
}
if reims.HasSMBIOSType17Arg(cur.ExtraArgs) {
return
}
supportsType := reims.ProbeQEMUSupportsSMBIOSMemoryType(p.Runtime.QemuPath(), p.Client.Env)
merged := reims.MergeSMBIOSType17Args(cur.ExtraArgs, rep.MemorySpec.SpeedMHz, rep.MemorySpec.MemoryType, supportsType)
if merged == cur.ExtraArgs {
return
}
if err := p.setExtraArgs(ctx, name, merged); err != nil {
return
}
cur.ExtraArgs = merged
}
func (p *Prep) setExtraArgs(ctx context.Context, name, args string) error {
return p.Client.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &args}, io.Discard, io.Discard)
}
// syncOfflineHelper attaches the REIMSHELP HFS+ helper disk while an offline
// installer is attached, and strips it once the installer is ejected. It also
// manages the per-VM REIMSPROV disk lifecycle.
func (p *Prep) syncOfflineHelper(ctx context.Context, name string, cur *reims.VMDetail) {
extra := cur.ExtraArgs
inRecovery := IsRecoveryMarkerActive(cur.Directory)
wipePending := installer.HasProvisionWipePending(cur.Directory)
staged := installer.HasProvisionStagedMarker(cur.Directory)
consumeStaged := false
if !wipePending && installer.HasProvisionImage(cur.Directory) && (cur.HasInstaller || inRecovery || staged) {
extra = reims.MergeProvisionArgs(extra, installer.ProvisionImagePath(cur.Directory))
if !cur.HasInstaller && !inRecovery && staged {
consumeStaged = true
}
} else {
extra = reims.StripProvisionArgs(extra)
if wipePending || (!cur.HasInstaller && !inRecovery) {
if err := installer.SecureRemoveProvisionImage(cur.Directory); err != nil {
p.log("Warning: could not remove offline provisioning disk (REIMSPROV): " + err.Error())
}
}
}
if cur.HasInstaller && reims.IsOfflineInstallerPath(cur.InstallerPath) {
p.log("Preparing offline install helper disk (REIMSHELP)...")
helperPath, err := installer.EnsureOfflineHelperImage(p.cfg.XDGCacheDir(), cur.InstallerPath)
if err != nil {
p.log("Warning: offline install helper disk skipped: " + err.Error())
} else {
extra = reims.MergeOfflineHelperArgs(extra, helperPath)
}
} else {
extra = reims.StripOfflineHelperArgs(extra)
}
if extra != cur.ExtraArgs {
if err := p.setExtraArgs(ctx, name, extra); err != nil {
p.log("Warning: could not update offline helper disks: " + err.Error())
return
}
cur.ExtraArgs = extra
}
// Only consume the one-shot staged marker after REIMSPROV args are committed
// so a failed setExtraArgs never causes the next cold start to wipe an unused image.
if consumeStaged {
installer.ClearProvisionStagedMarker(cur.Directory)
}
}
// syncRecoveryBootPicker applies a recovery-mode switch made while the VM was
// running: update-opencore needs a stopped VM (upstream 3731afd
// opencore.rs:400-402), so the switch is recorded in a marker file and done here.
func (p *Prep) syncRecoveryBootPicker(ctx context.Context, name string, cur *reims.VMDetail) {
var show bool
var done string
switch ReadRecoveryMarker(cur.Directory) {
case "want":
p.log("Enabling OpenCore boot picker for recovery mode...")
show, done = true, "on"
case "restore":
p.log("Restoring OpenCore direct boot after exiting recovery mode...")
show, done = false, ""
default:
return
}
w := vmstart.LineWriter(p.log)
if err := p.Client.UpdateOpenCore(ctx, name, show, w, w); err != nil {
p.log("Warning: could not update OpenCore boot picker: " + err.Error())
return
}
WriteRecoveryMarker(cur.Directory, done)
p.ReplayGuestLang(ctx, cur.Directory)
}
// applyProbedWHPXCompat pre-applies `-machine kernel-irqchip=off` on Windows 11
// builds where WHvPartitionPropertyCodeNestedVirtualization is probed as
// unsupported (e.g. hr=0x80370302) and the active runtime lacks
// qemu-whpx-nested-virt-nonfatal.patch, avoiding a first-start crash and retry.
func (p *Prep) applyProbedWHPXCompat(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) {
if rep.NeedsColdRebootWorkaround || !rep.WHPXCaps.KernelIrqchipAvailable || rep.WHPXCaps.NestedVirtProperty {
return
}
if p.RuntimeHasPatch("nested-virt-nonfatal") || reims.HasKernelIrqchipArg(cur.ExtraArgs) {
return
}
merged := reims.MergeKernelIrqchipOffArgs(cur.ExtraArgs)
if err := p.setExtraArgs(ctx, name, merged); err != nil {
return
}
cur.ExtraArgs = merged
code := rep.WHPXCaps.NestedVirtProbeError
if code == "" {
code = "unsupported"
}
p.log(i18n.M(p.cfg.Locale, "vmstart.compat.nested_virt", i18n.Vars{"code": code}))
}
// RuntimeHasPatch reports whether the active runtime was built with a patch
// whose name contains substr (case-insensitive).
func (p *Prep) RuntimeHasPatch(substr string) bool {
needle := strings.ToLower(substr)
for _, patch := range p.Runtime.Manifest.Patches {
if strings.Contains(strings.ToLower(patch.Name), needle) {
return true
}
}
return false
}
// ApplyGuestLang saves the VM's macOS prev-lang:kbd preference and, when the
// VM is stopped, writes it into the OpenCore image right away. A running VM
// gets it on its next start (ReplayGuestLang). An empty lang is a no-op.
func (p *Prep) ApplyGuestLang(ctx context.Context, vmDir, lang string, running bool) error {
norm, err := opencore.NormalizeGuestLang(lang)
if err != nil || norm == "" {
return err
}
if err := opencore.WriteSavedGuestLang(vmDir, norm); err != nil {
return err
}
if running {
p.log(fmt.Sprintf("Scheduled macOS boot/recovery language (%s) for next start", norm))
return nil
}
return p.patchGuestLang(ctx, vmDir, norm)
}
// ReplayGuestLang re-applies the saved language after anything that rebuilds
// the OpenCore image (update-opencore, a graphics switch, a clone) and before
// every start. Failures are logged, not returned: the VM still boots.
func (p *Prep) ReplayGuestLang(ctx context.Context, vmDir string) {
saved := opencore.ReadSavedGuestLang(vmDir)
if saved == "" {
return
}
if err := p.patchGuestLang(ctx, vmDir, saved); err != nil {
p.log(fmt.Sprintf("Warning: could not apply macOS language (%s) to OpenCore: %v", saved, err))
}
}
func (p *Prep) patchGuestLang(ctx context.Context, vmDir, lang string) error {
ocPath := opencore.ResolveOpenCorePath(vmDir)
if ocPath == "" {
return nil
}
changed, err := opencore.PatchImagePrevLang(ctx, ocPath, lang, p.Runtime.QemuImgPath(), p.Client.Env)
if err != nil {
return err
}
if changed {
p.log(fmt.Sprintf("Applied macOS boot/recovery language (%s) to OpenCore NVRAM", lang))
}
return nil
}
const recoveryMarkerFile = ".reims-go-recovery-picker"
// ReadRecoveryMarker returns the VM's pending recovery boot-picker state:
// "want" (enable on next start), "on" (enabled), "restore" (disable on next
// start) or "" (none).
func ReadRecoveryMarker(vmDir string) string {
if vmDir == "" {
return ""
}
b, err := os.ReadFile(filepath.Join(vmDir, recoveryMarkerFile))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
// IsRecoveryMarkerActive reports whether vmDir is currently in or scheduled to
// enter recovery mode ("on" or "want"), excluding "restore" (exiting recovery).
func IsRecoveryMarkerActive(vmDir string) bool {
m := ReadRecoveryMarker(vmDir)
return m == "on" || m == "want"
}
// WriteRecoveryMarker records state; "" removes the marker.
func WriteRecoveryMarker(vmDir, state string) {
if vmDir == "" {
return
}
p := filepath.Join(vmDir, recoveryMarkerFile)
if state == "" {
_ = os.Remove(p)
return
}
_ = os.WriteFile(p, []byte(state), 0o644)
}