* 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
342 lines
8.9 KiB
Go
342 lines
8.9 KiB
Go
package rules
|
|
|
|
import (
|
|
"embed"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"unicode"
|
|
)
|
|
|
|
//go:embed data/*.json
|
|
var builtinFS embed.FS
|
|
|
|
// RulePack is a pure declarative JSON rule collection (no executable scripts).
|
|
type RulePack struct {
|
|
Version int `json:"version"`
|
|
Rules []Rule `json:"rules"`
|
|
}
|
|
|
|
// Rule describes one page/modal recognition rule and its safe declarative actions.
|
|
type Rule struct {
|
|
ID string `json:"id"`
|
|
Stage string `json:"stage"` // "recovery" | "setup_assistant" | "desktop"
|
|
Priority int `json:"priority"`
|
|
RequiresSLA bool `json:"requires_sla,omitempty"`
|
|
AllowHighRisk bool `json:"allow_high_risk,omitempty"`
|
|
Match Match `json:"match"`
|
|
Actions []Action `json:"actions"`
|
|
Verify Verify `json:"verify,omitempty"`
|
|
}
|
|
|
|
type Match struct {
|
|
ROI string `json:"roi"`
|
|
AnyOf []string `json:"any_of"`
|
|
AllOf []string `json:"all_of,omitempty"`
|
|
Fuzzy bool `json:"fuzzy,omitempty"`
|
|
}
|
|
|
|
type Action struct {
|
|
Op string `json:"op"` // click_ocr | click_blue_button | key | ensure_checkbox | fill_account_form | select_pref_ocr | click_circle_or_key | pause_for_user
|
|
ROI string `json:"roi,omitempty"`
|
|
AnyOf []string `json:"any_of,omitempty"`
|
|
Fuzzy bool `json:"fuzzy,omitempty"`
|
|
Key string `json:"key,omitempty"`
|
|
Modifiers []string `json:"modifiers,omitempty"`
|
|
WantChecked *bool `json:"want_checked,omitempty"`
|
|
PrefKey string `json:"pref_key,omitempty"`
|
|
FallbackKey string `json:"fallback_key,omitempty"`
|
|
PauseReason string `json:"pause_reason,omitempty"`
|
|
}
|
|
|
|
type Verify struct {
|
|
WaitChangeMS int `json:"wait_change_ms,omitempty"`
|
|
MaxRetries int `json:"max_retries,omitempty"`
|
|
}
|
|
|
|
var allowedOps = map[string]bool{
|
|
"click_ocr": true,
|
|
"click_blue_button": true,
|
|
"key": true,
|
|
"ensure_checkbox": true,
|
|
"fill_account_form": true,
|
|
"select_pref_ocr": true,
|
|
"click_circle_or_key": true,
|
|
"pause_for_user": true,
|
|
}
|
|
|
|
var allowedStages = map[string]bool{
|
|
"recovery": true,
|
|
"setup_assistant": true,
|
|
"desktop": true,
|
|
}
|
|
|
|
// HighRiskKeywords trigger an immediate safety pause if present on screen and
|
|
// not explicitly handled by an AllowHighRisk rule.
|
|
var HighRiskKeywords = []string{
|
|
"erase", "抹掉", "抹除",
|
|
"recovery key", "恢复密钥", "復原密鑰",
|
|
"two-factor", "双重认证", "雙重認證",
|
|
"refusing to erase", "multiple eligible disks", "multiple candidate disks", "already has partitions", "[y/n]", "no writable target", "offline installer package not found",
|
|
"an error occurred", "发生错误", "安装失败", "installation failed",
|
|
"mac data will not be securely encrypted",
|
|
}
|
|
|
|
// TerminalHighRiskKeywords catches real abort, error, or interactive non-blank
|
|
// disk prompts from REIMSHELP/install.sh without falsely matching normal blank
|
|
// VM disk formatting ("Started erase on disk0" / "Finished erase on disk0").
|
|
var TerminalHighRiskKeywords = []string{
|
|
"refusing to erase",
|
|
"already has partitions",
|
|
"all data on it will be lost",
|
|
"multiple eligible disks",
|
|
"multiple candidate disks",
|
|
"[y/n]",
|
|
"no writable target",
|
|
"offline installer package not found",
|
|
"install macos app not found",
|
|
"command not found",
|
|
"no such file or directory",
|
|
"aborted",
|
|
"an error occurred",
|
|
"installation failed",
|
|
"发生错误",
|
|
"安装失败",
|
|
}
|
|
|
|
// Engine holds validated, priority-sorted declarative rules.
|
|
type Engine struct {
|
|
rules []Rule
|
|
}
|
|
|
|
// LoadEngine loads embedded built-in rule packs and overlays any user JSON
|
|
// rule patches found under <dataDir>/rules/*.json.
|
|
func LoadEngine(dataDir string) (*Engine, error) {
|
|
byID := map[string]Rule{}
|
|
|
|
entries, err := builtinFS.ReadDir("data")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, e := range entries {
|
|
if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") {
|
|
continue
|
|
}
|
|
raw, err := builtinFS.ReadFile("data/" + e.Name())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := mergePack(byID, raw, e.Name()); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
if strings.TrimSpace(dataDir) != "" {
|
|
userDir := filepath.Join(dataDir, "rules")
|
|
if userEntries, err := os.ReadDir(userDir); err == nil {
|
|
for _, e := range userEntries {
|
|
if e.IsDir() || !strings.HasSuffix(strings.ToLower(e.Name()), ".json") {
|
|
continue
|
|
}
|
|
raw, err := os.ReadFile(filepath.Join(userDir, e.Name()))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := mergePack(byID, raw, e.Name()); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
list := make([]Rule, 0, len(byID))
|
|
for _, r := range byID {
|
|
list = append(list, r)
|
|
}
|
|
sort.Slice(list, func(i, j int) bool {
|
|
if list[i].Priority != list[j].Priority {
|
|
return list[i].Priority > list[j].Priority
|
|
}
|
|
return list[i].ID < list[j].ID
|
|
})
|
|
return &Engine{rules: list}, nil
|
|
}
|
|
|
|
func mergePack(byID map[string]Rule, raw []byte, source string) error {
|
|
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
|
dec.DisallowUnknownFields()
|
|
var pack RulePack
|
|
if err := dec.Decode(&pack); err != nil {
|
|
return fmt.Errorf("parse rule pack %s: %w", source, err)
|
|
}
|
|
for _, r := range pack.Rules {
|
|
if err := validateRule(r); err != nil {
|
|
return fmt.Errorf("rule %q in %s: %w", r.ID, source, err)
|
|
}
|
|
byID[r.ID] = r
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateRule(r Rule) error {
|
|
if strings.TrimSpace(r.ID) == "" {
|
|
return fmt.Errorf("empty rule id")
|
|
}
|
|
if !allowedStages[r.Stage] {
|
|
return fmt.Errorf("unsupported stage %q", r.Stage)
|
|
}
|
|
if len(r.Match.AnyOf) == 0 && len(r.Match.AllOf) == 0 {
|
|
return fmt.Errorf("match must specify any_of or all_of")
|
|
}
|
|
if len(r.Actions) == 0 {
|
|
return fmt.Errorf("rule must declare at least one action")
|
|
}
|
|
for _, act := range r.Actions {
|
|
if !allowedOps[act.Op] {
|
|
return fmt.Errorf("unsupported action op %q", act.Op)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RulesForStage returns priority-ordered rules for stage.
|
|
func (e *Engine) RulesForStage(stage string) []Rule {
|
|
var out []Rule
|
|
for _, r := range e.rules {
|
|
if r.Stage == stage {
|
|
out = append(out, r)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// MatchScreen evaluates all rules for stage against ROI text maps (roiName -> full text).
|
|
func (e *Engine) MatchScreen(stage string, roiTexts map[string]string) (Rule, bool) {
|
|
for _, r := range e.rules {
|
|
if r.Stage != stage {
|
|
continue
|
|
}
|
|
text := roiTexts[r.Match.ROI]
|
|
if !hasMeaningfulOCRText(text) {
|
|
text = roiTexts["full"]
|
|
}
|
|
if matchesRuleText(r.Match, text) {
|
|
return r, true
|
|
}
|
|
}
|
|
return Rule{}, false
|
|
}
|
|
|
|
func hasMeaningfulOCRText(s string) bool {
|
|
letters := 0
|
|
for _, r := range NormalizeText(s) {
|
|
if unicode.IsLetter(r) {
|
|
letters++
|
|
if letters >= 2 {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func matchesRuleText(m Match, text string) bool {
|
|
if len(m.AnyOf) > 0 {
|
|
ok := false
|
|
for _, phrase := range m.AnyOf {
|
|
if MatchPhrase(text, phrase, m.Fuzzy) {
|
|
ok = true
|
|
break
|
|
}
|
|
}
|
|
if !ok {
|
|
return false
|
|
}
|
|
}
|
|
for _, phrase := range m.AllOf {
|
|
if !MatchPhrase(text, phrase, m.Fuzzy) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// DetectHighRiskKeyword returns the first matching high-risk keyword in text.
|
|
// Besides exact unnegated matching, it applies guarded fuzzy tolerance for
|
|
// single-character OCR noise (full fuzzy for long phrases >= 8 compact runes,
|
|
// and whole-word Levenshtein <= 1 for 5+ char ASCII words like "erase" so
|
|
// benign words like "please" or "ease" never false-positive).
|
|
func DetectHighRiskKeyword(text string) (string, bool) {
|
|
for _, kw := range HighRiskKeywords {
|
|
if matchHighRiskKeyword(text, kw) {
|
|
return kw, true
|
|
}
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
// DetectTerminalHighRiskKeyword checks Recovery Terminal output for real
|
|
// non-blank disk prompts or script errors while allowing normal blank-disk
|
|
// diskutil erase output.
|
|
func DetectTerminalHighRiskKeyword(text string) (string, bool) {
|
|
for _, kw := range TerminalHighRiskKeywords {
|
|
if matchHighRiskKeyword(text, kw) {
|
|
return kw, true
|
|
}
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
func matchHighRiskKeyword(text, kw string) bool {
|
|
if MatchPhrase(text, kw, false) {
|
|
return true
|
|
}
|
|
nc := CompactText(kw)
|
|
nr := []rune(nc)
|
|
if len(nr) >= 8 {
|
|
return MatchPhrase(text, kw, true)
|
|
}
|
|
// Whole-word fuzzy check for single ASCII high-risk words (e.g. "erase" vs OCR "erasc").
|
|
if len(nr) >= 5 && isPureASCIIWord(nc) {
|
|
return matchASCIIWordFuzzy(text, nr)
|
|
}
|
|
return false
|
|
}
|
|
|
|
func isPureASCIIWord(s string) bool {
|
|
if s == "" {
|
|
return false
|
|
}
|
|
for i := 0; i < len(s); i++ {
|
|
if !isASCIILetter(s[i]) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func matchASCIIWordFuzzy(text string, needle []rune) bool {
|
|
norm := NormalizeText(text)
|
|
if norm == "" {
|
|
return false
|
|
}
|
|
tokens := strings.FieldsFunc(norm, func(r rune) bool {
|
|
return !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '\''
|
|
})
|
|
for i, tok := range tokens {
|
|
if len(tok) < len(needle) || !isPureASCIIWord(tok) {
|
|
continue
|
|
}
|
|
if i > 0 && isPrecededByNegation(tokens[i-1]) {
|
|
continue
|
|
}
|
|
if levenshtein([]rune(tok), needle) <= 1 {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|