Files
Reims-Go/internal/app/console_router_test.go
球球 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

238 lines
7.9 KiB
Go

package app
import (
"context"
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/testutil/fakedriver"
)
type consoleTestApp struct {
app *App
drv driver.Driver
ref driver.VMRef
vmRoot string
svc *lifecycle.Service
harness *fakedriver.Harness
}
// newConsoleTestApp wires one hosted VM whose driver serves its own console.
func newConsoleTestApp(t *testing.T) *consoleTestApp {
t.Helper()
h := fakedriver.NewHarness(t)
drv := h.Add("hosted-console", "test.fake.console", "test.driver.console")
ctx := context.Background()
if err := drv.Create(ctx, driver.CreateRequest{DriverID: drv.ID(), Name: "dev"}, io.Discard, io.Discard); err != nil {
t.Fatal(err)
}
svc := lifecycle.New(h.Registry, h.Router, nil)
a := &App{
cfg: &config.Config{DataRoot: h.DataRoot},
transitions: map[string]string{},
pendingChanges: map[string][]PendingChange{},
pollWake: make(chan struct{}, 1),
diskPaths: map[string]cachedDiskPath{},
procSamples: map[string]host.ProcessSample{},
driverRouter: h.Router,
vmStateTable: h.States,
lifecycleSvc: svc,
}
t.Cleanup(func() { releaseVMThumbnailForDriver(drv.ID(), "dev") })
ct := &consoleTestApp{app: a, drv: drv, ref: driver.NewVMRef(drv.ID(), "dev"), svc: svc, harness: h,
vmRoot: filepath.Join(h.DataRoot, "vms", drv.ID())}
if _, err := svc.Start(ctx, ct.ref, io.Discard, io.Discard); err != nil {
t.Fatal(err)
}
waitFor(t, "the VM to run", func() bool {
vms, err := a.listVMsInternal(ctx)
if err != nil {
return false
}
for _, vm := range vms {
if vm.Name == "dev" && vm.State == "running" {
return true
}
}
return false
})
return ct
}
func (ct *consoleTestApp) log(t *testing.T) string {
t.Helper()
raw, _ := os.ReadFile(filepath.Join(ct.vmRoot, fakedriver.ConsoleLogName))
return string(raw)
}
func TestDriverConsoleRouteIsChosenForAConsoleDriver(t *testing.T) {
ct := newConsoleTestApp(t)
vm, err := ct.app.resolveVMInfo(ct.drv.ID(), "dev")
if err != nil {
t.Fatal(err)
}
route, err := ct.app.resolveConsoleRoute(vm)
if err != nil || route.kind != consoleRouteDriver || route.console == nil {
t.Fatalf("route = %+v, %v; want the driver console", route, err)
}
// A VM whose capabilities were narrowed below `console` loses the route.
vm.Capabilities = []string{driver.CapHosted}
if _, err := ct.app.resolveConsoleRoute(vm); err == nil {
t.Fatal("a VM without the console capability got a console route")
}
}
func TestDriverConsoleServesGUIThumbnailAndTyping(t *testing.T) {
ct := newConsoleTestApp(t)
a := ct.app
thumb, err := a.GetVMThumbnail(ct.drv.ID(), "dev")
if err != nil || !thumb.Live || !strings.HasPrefix(thumb.DataURL, "data:image/jpeg;base64,") {
t.Fatalf("thumbnail = live %v, %.30q, %v; want a live frame from the driver console", thumb.Live, thumb.DataURL, err)
}
n, err := a.TypeText(ct.drv.ID(), "dev", "hello")
if err != nil || n != 5 {
t.Fatalf("TypeText = %d, %v", n, err)
}
if got := ct.log(t); !strings.Contains(got, "type dev hello") {
t.Fatalf("the driver never received the text; its log is %q", got)
}
}
func TestDriverConsoleServesAgentInput(t *testing.T) {
ct := newConsoleTestApp(t)
a := ct.app
vm, err := a.resolveVMInfo(ct.drv.ID(), "dev")
if err != nil {
t.Fatal(err)
}
route, err := a.resolveConsoleRoute(vm)
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
if err := a.consolePointer(ctx, route, driver.ConsolePointerRequest{Action: "click", Button: "left"}); err != nil {
t.Fatal(err)
}
if err := a.consoleKey(ctx, route, "enter", []string{"shift"}); err != nil {
t.Fatal(err)
}
log := ct.log(t)
for _, want := range []string{"pointer dev click left", "key dev enter [shift]"} {
if !strings.Contains(log, want) {
t.Errorf("the driver log lacks %q: %q", want, log)
}
}
path, format, cleanup, err := a.consoleCapture(ctx, route, 1280)
if err != nil {
t.Fatal(err)
}
defer cleanup()
if format != "png" {
t.Fatalf("format = %q", format)
}
if st, err := os.Stat(path); err != nil || st.Size() == 0 {
t.Fatalf("frame file = %v, %v", st, err)
}
cleanup()
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatal("cleanup left the frame file behind")
}
}
// stubConsole is a driver console that writes its frame wherever it likes.
type stubConsole struct {
driver.ConsoleDriver
res driver.ConsoleScreenshotResult
file string // written when non-empty
}
func (s *stubConsole) ConsoleScreenshot(_ context.Context, _ string, req driver.ConsoleScreenshotRequest) (driver.ConsoleScreenshotResult, error) {
if s.file != "" {
if err := os.WriteFile(s.file, []byte("frame"), 0o644); err != nil {
return driver.ConsoleScreenshotResult{}, err
}
}
if s.res.Path == "" && s.file == "" {
if err := os.WriteFile(req.Path, []byte("frame"), 0o644); err != nil {
return driver.ConsoleScreenshotResult{}, err
}
}
return s.res, nil
}
func TestConsoleCaptureGuardsTheFramePathADriverReturns(t *testing.T) {
root := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: root}}
route := func(c driver.ConsoleDriver) consoleRoute {
return consoleRoute{kind: consoleRouteDriver, vm: driver.VMInfo{Name: "dev", DriverID: "acme.driver"}, console: c}
}
ctx := context.Background()
// The frame the host asked for is accepted and deleted by cleanup.
_, _, cleanup, err := a.consoleCapture(ctx, route(&stubConsole{}), 0)
if err != nil {
t.Fatalf("a frame at the requested path was rejected: %v", err)
}
cleanup()
// Any other file is rejected, even one inside the data folder.
own := filepath.Join(root, "own-frame.png")
if _, _, _, err := a.consoleCapture(ctx, route(&stubConsole{file: own, res: driver.ConsoleScreenshotResult{Path: own}}), 0); err == nil {
t.Fatal("a frame at a path the driver chose was accepted")
}
// An unsupported frame format is rejected.
if _, _, _, err := a.consoleCapture(ctx, route(&stubConsole{res: driver.ConsoleScreenshotResult{Format: "bmp"}}), 0); err == nil {
t.Fatal("an unsupported frame format was accepted")
}
}
func TestAgentCallsOnADriverConsoleVMAskForConfirmationInProtectedPhases(t *testing.T) {
ct := newConsoleTestApp(t)
a := ct.app
const plugin = "reims.agent"
a.markComputerUseOwnedVM(plugin, ct.ref.Key(), true) // grants access without a plugin manager
vm, route, err := a.resolveComputerUseVM(context.Background(), nil, plugin, ct.ref.Key(), false)
if err != nil || route.kind != consoleRouteDriver || vm.Name != "dev" {
t.Fatalf("a normal-phase driver console VM = %+v, %+v, %v", vm.Name, route.kind, err)
}
for _, phase := range []string{driver.PhaseInstaller, driver.PhaseRecovery} {
if err := os.WriteFile(filepath.Join(ct.vmRoot, "dev", "phase"), []byte(phase), 0o644); err != nil {
t.Fatal(err)
}
if _, _, err := a.resolveComputerUseVM(context.Background(), nil, plugin, ct.ref.Key(), false); err == nil || !strings.Contains(err.Error(), "confirmation_required") {
t.Fatalf("phase %s: err = %v, want confirmation_required", phase, err)
}
}
// A phase the host cannot read must not pass for the normal one.
if err := os.WriteFile(filepath.Join(ct.vmRoot, "dev", "phase"), []byte("bogus"), 0o644); err != nil {
t.Fatal(err)
}
if _, _, err := a.resolveComputerUseVM(context.Background(), nil, plugin, ct.ref.Key(), false); err == nil {
t.Fatal("a VM with an unreadable phase was treated as normal")
}
}
func TestComputerUsePhasePrefersTheDriverReportedPhase(t *testing.T) {
for phase, want := range map[string]string{
"": "normal",
driver.PhaseNormal: "normal",
driver.PhaseInstaller: "installer",
driver.PhaseRecovery: "recovery",
} {
if got := computerUseVMPhase(driver.VMInfo{Phase: phase}); got != want {
t.Errorf("phase %q -> %q, want %q", phase, got, want)
}
}
}