Skip to content

One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.

Beamer 1.5.15

Toby Kalkmanb3fcad8b8117
diff --git a/VERSION b/VERSION
index 8df6b88..f6ed435 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.5.14
+1.5.15
diff --git a/core/settings_sync.py b/core/settings_sync.py
index 371d76c..b818d13 100644
--- a/core/settings_sync.py
+++ b/core/settings_sync.py
@@ -19,6 +19,7 @@ settings, so the adapters read and write it there.
Never shared, whatever the switch says: zones (the ways, thirds and corner), `side`, the direction
switches, the Mac's notch way in and notch look, the haptics, whether crossings animate on each
screen, whether a full-screen app holds the edges, appearance, and per-system keyboard mapping.
+Windows administrator mode is a per-PC registry preference, outside settings and this protocol.
"""
import base64
diff --git a/core/tests/test_i18n_coverage.py b/core/tests/test_i18n_coverage.py
index 19d2b19..5f14a68 100644
--- a/core/tests/test_i18n_coverage.py
+++ b/core/tests/test_i18n_coverage.py
@@ -54,6 +54,10 @@ NOT_SHOWN = {
"beginActivityWithOptions_reason_", "asset_path", "CreateMutexW", "OpenMutexW", "QKeySequence",
"_turn_off_clashes", "exception", "_force_local", "stringForKey_", "open_dbus_connection", "update",
"require_version", "_log_helper_failure",
+ "report_input_problem", # Operation names are log diagnostics; the blocker supplies translated UI text.
+ # XML paths and scheduled-task run levels are Windows data, not translated prose.
+ "find", "findall", "findtext", "SubElement", "task_xml",
+ "_FlagAsMethod", # COM method identifiers must retain their registered spelling.
}
diff --git a/core/tests/test_settings_sync.py b/core/tests/test_settings_sync.py
index 5b340b6..b36acb5 100644
--- a/core/tests/test_settings_sync.py
+++ b/core/tests/test_settings_sync.py
@@ -45,6 +45,17 @@ def pc_config(**fields):
class MessageTests(unittest.TestCase):
+ def test_admin_mode_is_never_transmitted_or_applied(self):
+ config = pc_config(run_as_administrator=True)
+ self.assertNotIn("run_as_administrator", settings_sync.pc_values(config))
+ data = settings_sync.message_data(True, 1, {"run_as_administrator": True})
+ self.assertNotIn("run_as_administrator", data["crossing"])
+ self.assertNotIn("run_as_administrator", data["design"])
+ settings_sync.apply_pc(config, {"run_as_administrator": False})
+ self.assertTrue(config.run_as_administrator)
+ raw = mac_raw()
+ self.assertNotIn("run_as_administrator", settings_sync.apply_mac(raw, {"run_as_administrator": True}))
+
def test_pc_modifier_style_is_local_and_not_part_of_same_on_all_machines(self):
self.assertNotIn("modifier_style", settings_sync.CROSSING_KEYS + settings_sync.DESIGN_KEYS)
diff --git a/flatpak/uk.co.kalkman.beamer.metainfo.xml b/flatpak/uk.co.kalkman.beamer.metainfo.xml
index db32ec6..fddfb6a 100644
--- a/flatpak/uk.co.kalkman.beamer.metainfo.xml
+++ b/flatpak/uk.co.kalkman.beamer.metainfo.xml
@@ -43,6 +43,9 @@
</screenshots>
<content_rating type="oars-1.1"/>
<releases>
+ <release version="1.5.15" date="2026-10-27">
+ <description><p>On Windows, a new setting, Control administrator windows, lets Beamer move the pointer and type in apps that run as administrator. It is off by default, asks for permission once, and applies only to that PC. When Windows blocks Beamer's input, the notice now names the app in front and appears once for each window, not on every switch, and the firewall check says when it needs administrator permission.</p></description>
+ </release>
<release version="1.5.14" date="2026-10-26">
<description><p>Scrolling a settings page no longer changes a slider or a drop-down list that the pointer stops over: a control takes the scroll wheel only after it is clicked or reached with the keyboard. When a Windows PC, another Mac or a Linux PC on X11 drives a Mac, holding a letter now opens the macOS accent menu in apps that offer it.</p></description>
</release>
diff --git a/locales/beamer.pot b/locales/beamer.pot
index 846a497..f9d6018 100644
--- a/locales/beamer.pot
+++ b/locales/beamer.pot
@@ -3970,6 +3970,50 @@ msgstr ""
msgid "{name}, needs attention"
msgstr ""
+#: win_app/admin_mode.py
+msgid "This setting is only available on Windows."
+msgstr ""
+
+#: win_app/admin_mode.py
+msgid "Install Beamer to control administrator windows. This setting is unavailable in portable mode."
+msgstr ""
+
+#: win_app/admin_mode.py
+msgid "This setting needs Beamer to run as the signed-in account."
+msgstr ""
+
+#: win_app/admin_mode.py
+msgid "This setting needs a Windows administrator account."
+msgstr ""
+
+#: win_app/admin_mode.py
+msgid "Enable Windows User Account Control to use this setting."
+msgstr ""
+
+#: win_app/admin_mode.py
+msgid "Windows could not check this account's administrator permission."
+msgstr ""
+
+#: win_app/admin_mode.py
+msgid "Windows could not start the administrator setting change."
+msgstr ""
+
+#: win_app/admin_mode.py
+msgid "The administrator setting could not be changed. Your previous setting has been kept."
+msgstr ""
+
+#: win_app/admin_mode.py
+msgid "Start at sign-in could not be changed. Your previous setting has been kept."
+msgstr ""
+
+#: win_app/admin_mode.py
+msgid "Windows could not find the desktop shell. Start Windows Explorer and try again. Your previous setting has been kept."
+msgstr ""
+
+#: win_app/admin_mode.py
+msgid "Administrator permission was cancelled. Your previous setting has been kept."
+msgstr ""
+
#: win_app/crossing_ledger.py
msgid "Return saves, Escape cancels · Only on this PC"
msgstr ""
@@ -4180,20 +4224,23 @@ msgid "Check again"
msgstr ""
#: win_app/firewall_win.py
-msgid "Windows Firewall has a block rule affecting Beamer's input or pairing traffic; ask your administrator to review Beamer's inbound block rules in Windows Firewall."
+msgid "Beamer cannot check Windows Firewall without administrator permission; run the Beamer installer again to repair its rules."
msgstr ""
#: win_app/firewall_win.py
-msgid "this private network"
+msgid "Beamer could not check Windows Firewall. Check again; if the problem continues, run the Beamer installer again to repair its rules."
msgstr ""
#: win_app/firewall_win.py
-msgid "this network"
+msgid "Windows Firewall has a block rule affecting Beamer's input or pairing traffic; ask your administrator to review Beamer's inbound block rules in Windows Firewall."
msgstr ""
#: win_app/firewall_win.py
-#, python-brace-format
-msgid "Beamer could not read the Windows Firewall: {error}"
+msgid "this private network"
+msgstr ""
+
+#: win_app/firewall_win.py
+msgid "this network"
msgstr ""
#: win_app/firewall_win.py
@@ -4219,8 +4266,33 @@ msgstr ""
msgid "Beamer — Identify screens"
msgstr ""
-#: win_app/input_injector.py
-msgid "Windows blocked Beamer's input; use administrator windows locally and click a normal window on this PC to continue."
+#: win_app/input_blocker.py
+msgid "the foreground window"
+msgstr ""
+
+#: win_app/input_blocker.py
+#, python-brace-format
+msgid "Windows blocked Beamer's input while {app} was in front. Click a normal window on this PC to continue."
+msgstr ""
+
+#: win_app/input_blocker.py
+#, python-brace-format
+msgid "Windows blocked Beamer's input because {app} is GameInput's system window. Click a normal window on this PC to continue."
+msgstr ""
+
+#: win_app/input_blocker.py
+#, python-brace-format
+msgid "Windows blocked Beamer's input because {app} is a system-level window. Use it locally and click a normal window on this PC to continue."
+msgstr ""
+
+#: win_app/input_blocker.py
+#, python-brace-format
+msgid "Windows blocked Beamer's input because {app} is running as administrator. Click a normal window on this PC to continue."
+msgstr ""
+
+#: win_app/input_blocker.py
+#, python-brace-format
+msgid "Windows blocked Beamer's input while {app} was in front. Windows did not allow Beamer to inspect this window's process. Click a normal window on this PC to continue."
msgstr ""
#: win_app/kvm_bridge_win.py
@@ -4365,6 +4437,14 @@ msgstr ""
msgid "On Wayland Beamer cannot see a full-screen app, or a mouse button held before the pointer reaches an edge, so the edges are never held for one and a drag can cross."
msgstr ""
+#: win_app/kvm_bridge_win.py
+msgid "Control administrator windows"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Waiting for Windows permission…"
+msgstr ""
+
#: win_app/kvm_bridge_win.py
msgid "At sign-in"
msgstr ""
@@ -4551,6 +4631,18 @@ msgstr ""
msgid "Delay:"
msgstr ""
+#: win_app/kvm_bridge_win.py
+msgid "Use Windows permission prompts locally."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Beamer could not read this PC's administrator setting. Restart Beamer to try again."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Beamer will run as administrator on this PC. Changing this restarts Beamer; Windows may ask for permission."
+msgstr ""
+
#: win_app/kvm_bridge_win.py
msgid "Start at sign-in needs Beamer to run as the signed-in account."
msgstr ""
@@ -4640,10 +4732,6 @@ msgstr ""
msgid "Update through your software store, or download the Flatpak from the release page and open it."
msgstr ""
-#: win_app/kvm_bridge_win.py
-msgid "Beamer controls normal windows; use administrator windows and Windows permission prompts locally."
-msgstr ""
-
#: win_app/kvm_bridge_win.py
msgid "Starts in the tray when you sign in, without an administrator prompt."
msgstr ""
diff --git a/locales/it.po b/locales/it.po
index 48fe320..b764b06 100644
--- a/locales/it.po
+++ b/locales/it.po
@@ -4030,6 +4030,50 @@ msgstr "{name} ⌘{key}"
msgid "{name}, needs attention"
msgstr "{name}, richiede attenzione"
+#: win_app/admin_mode.py
+msgid "This setting is only available on Windows."
+msgstr "Questa impostazione è disponibile solo su Windows."
+
+#: win_app/admin_mode.py
+msgid "Install Beamer to control administrator windows. This setting is unavailable in portable mode."
+msgstr "Installa Beamer per controllare le finestre con privilegi di amministratore. Questa impostazione non è disponibile in modalità portatile."
+
+#: win_app/admin_mode.py
+msgid "This setting needs Beamer to run as the signed-in account."
+msgstr "Questa impostazione richiede che Beamer venga eseguito con l'account attualmente connesso."
+
+#: win_app/admin_mode.py
+msgid "This setting needs a Windows administrator account."
+msgstr "Questa impostazione richiede un account amministratore di Windows."
+
+#: win_app/admin_mode.py
+msgid "Enable Windows User Account Control to use this setting."
+msgstr "Attiva il Controllo dell'account utente di Windows per usare questa impostazione."
+
+#: win_app/admin_mode.py
+msgid "Windows could not check this account's administrator permission."
+msgstr "Windows non ha potuto verificare i privilegi di amministratore di questo account."
+
+#: win_app/admin_mode.py
+msgid "Windows could not start the administrator setting change."
+msgstr "Windows non ha potuto avviare la modifica dell'impostazione dei privilegi di amministratore."
+
+#: win_app/admin_mode.py
+msgid "The administrator setting could not be changed. Your previous setting has been kept."
+msgstr "Non è stato possibile modificare l'impostazione dei privilegi di amministratore. L'impostazione precedente è stata mantenuta."
+
+#: win_app/admin_mode.py
+msgid "Start at sign-in could not be changed. Your previous setting has been kept."
+msgstr "Non è stato possibile modificare l'avvio all'accesso. L'impostazione precedente è stata mantenuta."
+
+#: win_app/admin_mode.py
+msgid "Windows could not find the desktop shell. Start Windows Explorer and try again. Your previous setting has been kept."
+msgstr "Windows non ha trovato la shell del desktop. Avvia Esplora file e riprova. L'impostazione precedente è stata mantenuta."
+
+#: win_app/admin_mode.py
+msgid "Administrator permission was cancelled. Your previous setting has been kept."
+msgstr "La richiesta dei privilegi di amministratore è stata annullata. L'impostazione precedente è stata mantenuta."
+
#: win_app/crossing_ledger.py
msgid "Return saves, Escape cancels · Only on this PC"
msgstr "Invio salva, Esc annulla · Solo su questo PC"
@@ -4241,6 +4285,16 @@ msgstr "Le regole del firewall di Beamer vanno corrette; esegui di nuovo il prog
msgid "Check again"
msgstr "Controlla di nuovo"
+# New in 1.5.15: English fallback awaiting Lorenzo's check
+#: win_app/firewall_win.py
+msgid "Beamer cannot check Windows Firewall without administrator permission; run the Beamer installer again to repair its rules."
+msgstr "Beamer cannot check Windows Firewall without administrator permission; run the Beamer installer again to repair its rules."
+
+# New in 1.5.15: English fallback awaiting Lorenzo's check
+#: win_app/firewall_win.py
+msgid "Beamer could not check Windows Firewall. Check again; if the problem continues, run the Beamer installer again to repair its rules."
+msgstr "Beamer could not check Windows Firewall. Check again; if the problem continues, run the Beamer installer again to repair its rules."
+
#: win_app/firewall_win.py
msgid "Windows Firewall has a block rule affecting Beamer's input or pairing traffic; ask your administrator to review Beamer's inbound block rules in Windows Firewall."
msgstr "Una regola di blocco del Firewall di Windows riguarda il traffico di input o di abbinamento di Beamer; chiedi all'amministratore di controllare le regole di blocco in entrata di Beamer nel Firewall di Windows."
@@ -4253,11 +4307,6 @@ msgstr "questa rete privata"
msgid "this network"
msgstr "questa rete"
-#: win_app/firewall_win.py
-#, python-brace-format
-msgid "Beamer could not read the Windows Firewall: {error}"
-msgstr "Beamer non è riuscito a leggere Windows Firewall: {error}"
-
#: win_app/firewall_win.py
#, python-brace-format
msgid "Windows Firewall lets your other machines reach Beamer on port {port} on {where}, and lets a new machine discover this PC."
@@ -4281,9 +4330,40 @@ msgstr "Invia input a un altro computer"
msgid "Beamer — Identify screens"
msgstr "Beamer — Identifica gli schermi"
-#: win_app/input_injector.py
-msgid "Windows blocked Beamer's input; use administrator windows locally and click a normal window on this PC to continue."
-msgstr "Windows ha bloccato l'input di Beamer; usa localmente le finestre con privilegi di amministratore e fai clic su una finestra normale di questo PC per continuare."
+# New in 1.5.15: English fallback awaiting Lorenzo's check
+#: win_app/input_blocker.py
+msgid "the foreground window"
+msgstr "the foreground window"
+
+# New in 1.5.15: English fallback awaiting Lorenzo's check
+#: win_app/input_blocker.py
+#, python-brace-format
+msgid "Windows blocked Beamer's input while {app} was in front. Click a normal window on this PC to continue."
+msgstr "Windows blocked Beamer's input while {app} was in front. Click a normal window on this PC to continue."
+
+# New in 1.5.15: English fallback awaiting Lorenzo's check
+#: win_app/input_blocker.py
+#, python-brace-format
+msgid "Windows blocked Beamer's input because {app} is GameInput's system window. Click a normal window on this PC to continue."
+msgstr "Windows blocked Beamer's input because {app} is GameInput's system window. Click a normal window on this PC to continue."
+
+# New in 1.5.15: English fallback awaiting Lorenzo's check
+#: win_app/input_blocker.py
+#, python-brace-format
+msgid "Windows blocked Beamer's input because {app} is a system-level window. Use it locally and click a normal window on this PC to continue."
+msgstr "Windows blocked Beamer's input because {app} is a system-level window. Use it locally and click a normal window on this PC to continue."
+
+# New in 1.5.15: English fallback awaiting Lorenzo's check
+#: win_app/input_blocker.py
+#, python-brace-format
+msgid "Windows blocked Beamer's input because {app} is running as administrator. Click a normal window on this PC to continue."
+msgstr "Windows blocked Beamer's input because {app} is running as administrator. Click a normal window on this PC to continue."
+
+# New in 1.5.15: English fallback awaiting Lorenzo's check
+#: win_app/input_blocker.py
+#, python-brace-format
+msgid "Windows blocked Beamer's input while {app} was in front. Windows did not allow Beamer to inspect this window's process. Click a normal window on this PC to continue."
+msgstr "Windows blocked Beamer's input while {app} was in front. Windows did not allow Beamer to inspect this window's process. Click a normal window on this PC to continue."
#: win_app/kvm_bridge_win.py
msgid "Beamer's website"
@@ -4427,6 +4507,14 @@ msgstr "Su Wayland è l'ambiente desktop a gestire la visibilità del puntatore
msgid "On Wayland Beamer cannot see a full-screen app, or a mouse button held before the pointer reaches an edge, so the edges are never held for one and a drag can cross."
msgstr "Su Wayland Beamer non vede un'app a schermo intero, né un pulsante del mouse tenuto premuto prima che il puntatore raggiunga un bordo, quindi i bordi non vengono mai bloccati per un'app e un trascinamento può passare."
+#: win_app/kvm_bridge_win.py
+msgid "Control administrator windows"
+msgstr "Controlla le finestre con privilegi di amministratore"
+
+#: win_app/kvm_bridge_win.py
+msgid "Waiting for Windows permission…"
+msgstr "In attesa dell'autorizzazione di Windows…"
+
#: win_app/kvm_bridge_win.py
msgid "At sign-in"
msgstr "All'accesso"
@@ -4617,6 +4705,18 @@ msgstr "Input:"
msgid "Delay:"
msgstr "Ritardo:"
+#: win_app/kvm_bridge_win.py
+msgid "Use Windows permission prompts locally."
+msgstr "Gestisci localmente le richieste di autorizzazione di Windows."
+
+#: win_app/kvm_bridge_win.py
+msgid "Beamer could not read this PC's administrator setting. Restart Beamer to try again."
+msgstr "Beamer non ha potuto leggere l'impostazione dei privilegi di amministratore di questo PC. Riavvia Beamer per riprovare."
+
+#: win_app/kvm_bridge_win.py
+msgid "Beamer will run as administrator on this PC. Changing this restarts Beamer; Windows may ask for permission."
+msgstr "Beamer verrà eseguito come amministratore su questo PC. La modifica riavvia Beamer; Windows potrebbe chiedere l'autorizzazione."
+
#: win_app/kvm_bridge_win.py
msgid "Start at sign-in needs Beamer to run as the signed-in account."
msgstr "Per avviarsi all'accesso, Beamer deve essere eseguito con l'account attualmente connesso."
@@ -4708,10 +4808,6 @@ msgstr "Questo desktop non ha un'area di notifica, quindi la finestra di Beamer
msgid "Update through your software store, or download the Flatpak from the release page and open it."
msgstr "Aggiorna tramite il tuo negozio di software oppure scarica il file Flatpak dalla pagina della versione e aprilo."
-#: win_app/kvm_bridge_win.py
-msgid "Beamer controls normal windows; use administrator windows and Windows permission prompts locally."
-msgstr "Beamer controlla le finestre normali; gestisci localmente le finestre con privilegi di amministratore e le richieste di autorizzazione di Windows."
-
#: win_app/kvm_bridge_win.py
msgid "Starts in the tray when you sign in, without an administrator prompt."
msgstr "All'accesso si avvia nell'area di notifica, senza richiesta di privilegi di amministratore."
diff --git a/win_app/Install-Maintenance.ps1 b/win_app/Install-Maintenance.ps1
index ee86876..b60d633 100644
--- a/win_app/Install-Maintenance.ps1
+++ b/win_app/Install-Maintenance.ps1
@@ -14,8 +14,22 @@ function Resolve-BeamerUserSid([string]$Identity) {
return ([Security.Principal.NTAccount]$Identity).Translate([Security.Principal.SecurityIdentifier]).Value
}
+function Get-BeamerAdministratorPreference([string]$UserSid) {
+ $key = [Microsoft.Win32.Registry]::Users.OpenSubKey("$UserSid\Software\KalkmanCode\Beamer")
+ if ($null -eq $key) { return $false }
+ try {
+ if ($key.GetValueKind('RunAsAdministrator') -ne [Microsoft.Win32.RegistryValueKind]::DWord) { return $false }
+ return $key.GetValue('RunAsAdministrator', 0) -eq 1
+ } catch [System.IO.IOException] {
+ return $false
+ } finally {
+ $key.Dispose()
+ }
+}
+
function Update-BeamerAutostart([string]$ExePath, [string]$UserSid, [switch]$Remove) {
$expectedPath = [IO.Path]::GetFullPath($ExePath)
+ $runLevel = if (-not $Remove -and (Get-BeamerAdministratorPreference -UserSid $UserSid)) { 'HighestAvailable' } else { 'LeastPrivilege' }
foreach ($task in @(Get-ScheduledTask -TaskPath '\' -ErrorAction Stop)) {
if ($task.TaskName -ne 'Beamer' -and $task.TaskName -notlike 'Beamer-*') { continue }
[xml]$xml = Export-ScheduledTask -TaskName $task.TaskName -TaskPath '\' -ErrorAction Stop
@@ -36,9 +50,15 @@ function Update-BeamerAutostart([string]$ExePath, [string]$UserSid, [switch]$Rem
Unregister-ScheduledTask -TaskName $task.TaskName -TaskPath '\' -Confirm:$false -ErrorAction Stop
continue
}
- if ($principal.RunLevel -ne 'HighestAvailable') { continue }
+ $runLevelNode = $principal.SelectSingleNode('t:RunLevel', $ns)
+ $currentRunLevel = if ($null -eq $runLevelNode) { 'LeastPrivilege' } else { $runLevelNode.InnerText }
+ if ($currentRunLevel -eq $runLevel) { continue }
# Keep the existing task definition: disabled startup, arguments and logon triggers are user choices.
- $principal.RunLevel = 'LeastPrivilege'
+ if ($null -eq $runLevelNode) {
+ $runLevelNode = $xml.CreateElement('RunLevel', $principal.NamespaceURI)
+ [void]$principal.AppendChild($runLevelNode)
+ }
+ $runLevelNode.InnerText = $runLevel
Register-ScheduledTask -TaskName $task.TaskName -TaskPath '\' -Xml $xml.OuterXml -Force -ErrorAction Stop | Out-Null
}
}
@@ -77,6 +97,39 @@ function Repair-BeamerGameInput {
}
}
+function Update-BeamerGameInputRecovery([switch]$Remove) {
+ $taskName = 'Beamer-GameInputRecovery'
+ if ($Remove) {
+ if (Get-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction SilentlyContinue) {
+ Unregister-ScheduledTask -TaskName $taskName -TaskPath '\' -Confirm:$false -ErrorAction Stop
+ }
+ return
+ }
+
+ $scheduler = New-Object -ComObject 'Schedule.Service'
+ $scheduler.Connect()
+ $folder = $scheduler.GetFolder('\')
+ $definition = $scheduler.NewTask(0)
+ $definition.RegistrationInfo.Description = 'Restarts GameInput when its service window blocks remote pointer control.'
+ $definition.Principal.UserId = 'S-1-5-18'
+ $definition.Principal.LogonType = 5
+ $definition.Principal.RunLevel = 1
+ $definition.Settings.Enabled = $true
+ $definition.Settings.AllowDemandStart = $true
+ $definition.Settings.DisallowStartIfOnBatteries = $false
+ $definition.Settings.StopIfGoingOnBatteries = $false
+ $definition.Settings.ExecutionTimeLimit = 'PT30S'
+ $definition.Settings.MultipleInstances = 2
+ $windows = [Environment]::GetFolderPath([Environment+SpecialFolder]::Windows)
+ $action = $definition.Actions.Create(0)
+ $action.Path = Join-Path $windows 'System32\WindowsPowerShell\v1.0\powershell.exe'
+ $action.Arguments = '-NoLogo -NoProfile -NonInteractive -Command "Restart-Service -Name ''GameInputSvc'' -ErrorAction Stop"'
+ $action.WorkingDirectory = Join-Path $windows 'System32'
+ # Set the protected ACL at registration: no interval with an elevated, user-writable task.
+ $sddl = 'O:SYG:SYD:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGX;;;IU)'
+ $folder.RegisterTaskDefinition($taskName, $definition, (0x6 -bor 0x10), 'S-1-5-18', $null, 5, $sddl) | Out-Null
+}
+
if ($MyInvocation.InvocationName -ne '.') {
try {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
@@ -91,9 +144,11 @@ if ($MyInvocation.InvocationName -ne '.') {
$UserSid = ([Security.Principal.SecurityIdentifier]$UserSid).Value
Update-BeamerAutostart -ExePath $ExePath -UserSid $UserSid -Remove:$Remove
if ($Remove) {
+ Update-BeamerGameInputRecovery -Remove
Remove-BeamerFirewall -ExePath $ExePath
} else {
Repair-BeamerFirewall -ExePath $ExePath
+ Update-BeamerGameInputRecovery
Repair-BeamerGameInput
}
exit 0
diff --git a/win_app/admin_mode.py b/win_app/admin_mode.py
new file mode 100644
index 0000000..7b8e2af
--- /dev/null
+++ b/win_app/admin_mode.py
@@ -0,0 +1,346 @@
+"""Opt-in elevation belongs to this Windows account, never the paired settings file."""
+
+from __future__ import annotations
+
+import copy
+import logging
+import ntpath
+import os
+import subprocess
+import sys
+import tempfile
+import xml.etree.ElementTree as ET
+
+from core.i18n import tr
+import autostart_win
+
+
+LOGGER = logging.getLogger(__name__)
+REGISTRY_PATH = r"Software\KalkmanCode\Beamer"
+REGISTRY_VALUE = "RunAsAdministrator"
+NS = "{http://schemas.microsoft.com/windows/2004/02/mit/task}"
+DESKTOP_SHELL_UNAVAILABLE = 2
+
+
+class DesktopShellUnavailable(OSError):
+ pass
+
+
+def _read_preference():
+ import winreg
+ try:
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, REGISTRY_PATH) as key:
+ return winreg.QueryValueEx(key, REGISTRY_VALUE)
+ except FileNotFoundError:
+ return None
+
+
+def enabled() -> bool:
+ if sys.platform != "win32":
+ return False
+ try:
+ import winreg
+ return _read_preference() == (1, winreg.REG_DWORD)
+ except OSError:
+ return False
+
+
+def _write_preference(value: bool) -> None:
+ import winreg
+ with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, REGISTRY_PATH, 0, winreg.KEY_SET_VALUE) as key:
+ winreg.SetValueEx(key, REGISTRY_VALUE, 0, winreg.REG_DWORD, int(value))
+
+
+def _restore_preference(previous) -> None:
+ import winreg
+ if previous is not None:
+ with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, REGISTRY_PATH, 0, winreg.KEY_SET_VALUE) as key:
+ winreg.SetValueEx(key, REGISTRY_VALUE, 0, previous[1], previous[0])
+ return
+ try:
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, REGISTRY_PATH, 0, winreg.KEY_SET_VALUE) as key:
+ winreg.DeleteValue(key, REGISTRY_VALUE)
+ except FileNotFoundError:
+ pass
+
+
+def _token_information(kind):
+ import win32api
+ import win32con
+ import win32security
+ token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
+ try:
+ return win32security.GetTokenInformation(token, kind)
+ finally:
+ token.Close()
+
+
+def _administrator_account() -> bool:
+ import win32security
+ # A split administrator's medium token has its administrator group disabled.
+ return bool(_token_information(win32security.TokenElevation)) or _token_information(win32security.TokenElevationType) == 3
+
+
+def _is_elevated() -> bool:
+ if sys.platform != "win32":
+ return False
+ import win32security
+ return bool(_token_information(win32security.TokenElevation))
+
+
+def unavailable_reason() -> str:
+ if sys.platform != "win32":
+ return tr("This setting is only available on Windows.")
+ if autostart_win.installed_exe() is None:
+ return tr("Install Beamer to control administrator windows. This setting is unavailable in portable mode.")
+ try:
+ if not autostart_win.can_run_for_current_user():
+ return tr("This setting needs Beamer to run as the signed-in account.")
+ if not _administrator_account():
+ return tr("This setting needs a Windows administrator account.")
+ import win32security
+ if _token_information(win32security.TokenElevationType) not in (2, 3):
+ return tr("Enable Windows User Account Control to use this setting.")
+ except Exception:
+ return tr("Windows could not check this account's administrator permission.")
+ return ""
+
+
+def _run_elevated_helper(value: bool, config_path=None, *, startup_only=False, hidden=True) -> None:
+ import pythoncom
+ import win32api
+ import win32event
+ from win32com.shell import shell
+ arguments = ["--set-admin-startup" if startup_only else "--set-admin-mode", "on" if value else "off"]
+ if config_path is not None:
+ arguments.extend(["--config", os.path.abspath(str(config_path))])
+ if not hidden and not startup_only:
+ arguments.append("--show")
+ pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
+ try:
+ result = shell.ShellExecuteEx(
+ fMask=0x40 | 0x100, lpVerb="runas", lpFile=sys.executable,
+ lpParameters=subprocess.list2cmdline(arguments),
+ lpDirectory=os.path.dirname(sys.executable), nShow=0,
+ )
+ process = result.get("hProcess")
+ if process is None:
+ raise OSError(tr("Windows could not start the administrator setting change."))
+ try:
+ win32event.WaitForSingleObject(process, win32event.INFINITE)
+ import win32process
+ result_code = win32process.GetExitCodeProcess(process)
+ if result_code == DESKTOP_SHELL_UNAVAILABLE:
+ raise OSError(tr("Windows could not find the desktop shell. Start Windows Explorer and try again. Your previous setting has been kept."))
+ if result_code != 0:
+ raise OSError(tr("The administrator setting could not be changed. Your previous setting has been kept."))
+ finally:
+ win32api.CloseHandle(process)
+ finally:
+ pythoncom.CoUninitialize()
+
+
+def change(value: bool, config_path=None) -> bool:
+ reason = unavailable_reason()
+ if reason:
+ raise OSError(reason)
+ if bool(value) == enabled():
+ return False
+ try:
+ # The switch lives on the visible Settings page, so the replacement reopens it.
+ _run_elevated_helper(bool(value), config_path, hidden=False)
+ except Exception as exc:
+ if getattr(exc, "winerror", None) == 1223 or getattr(exc, "errno", None) == 1223:
+ raise OSError(tr("Administrator permission was cancelled. Your previous setting has been kept.")) from exc
+ if isinstance(exc, OSError):
+ raise
+ raise OSError(tr("The administrator setting could not be changed. Your previous setting has been kept.")) from exc
+ return True
+
+
+def change_startup(value: bool) -> None:
+ reason = unavailable_reason()
+ if reason:
+ raise OSError(reason)
+ try:
+ _run_elevated_helper(value, startup_only=True)
+ except Exception as exc:
+ if getattr(exc, "winerror", None) == 1223 or getattr(exc, "errno", None) == 1223:
+ raise OSError(tr("Administrator permission was cancelled. Your previous setting has been kept.")) from exc
+ raise OSError(tr("Start at sign-in could not be changed. Your previous setting has been kept.")) from exc
+
+
+def relaunch_if_required(config_path=None, *, hidden=True) -> bool:
+ if sys.platform != "win32" or not enabled() or unavailable_reason():
+ return False
+ import win32security
+ if _token_information(win32security.TokenElevation):
+ return False
+ try:
+ if hidden:
+ _run_elevated_helper(True, config_path)
+ else:
+ _run_elevated_helper(True, config_path, hidden=False)
+ except Exception as exc:
+ if getattr(exc, "winerror", None) == 1223 or getattr(exc, "errno", None) == 1223:
+ raise OSError(tr("Administrator permission was cancelled. Your previous setting has been kept.")) from exc
+ raise OSError(tr("The administrator setting could not be changed. Your previous setting has been kept.")) from exc
+ return True
+
+
+def _register_task(name: str, root, run) -> None:
+ descriptor, path = tempfile.mkstemp(suffix=".xml")
+ try:
+ with os.fdopen(descriptor, "w", encoding="utf-16") as handle:
+ handle.write(ET.tostring(root, encoding="unicode"))
+ result = run(["schtasks", "/create", "/tn", name, "/xml", path, "/f"])
+ if result.returncode:
+ raise OSError((result.stderr or result.stdout or "Windows could not update Beamer's sign-in task").strip())
+ finally:
+ os.unlink(path)
+
+
+def _checked_task(root, exe: str, user: str):
+ principals = root.findall(NS + "Principals/" + NS + "Principal")
+ actions = root.findall(NS + "Actions/*")
+ if len(principals) != 1 or len(actions) != 1 or actions[0].tag != NS + "Exec":
+ raise OSError("Beamer's sign-in task has an unexpected definition")
+ principal = principals[0]
+ owner = principal.findtext(NS + "UserId", "")
+ if owner.casefold() != user.casefold() and owner.casefold() != autostart_win._user_sid(user).casefold():
+ raise OSError("Beamer's sign-in task belongs to a different account")
+ command = actions[0].findtext(NS + "Command", "").strip('"')
+ if (principal.findtext(NS + "LogonType") != "InteractiveToken"
+ or ntpath.normcase(command) != ntpath.normcase(exe)):
+ raise OSError("Beamer's sign-in task does not start this installed app")
+ level = principal.find(NS + "RunLevel")
+ if level is None:
+ level = ET.SubElement(principal, NS + "RunLevel")
+ return level
+
+
+def _transition(value: bool, exe: str, user: str, run=autostart_win._run, *, config_path=None, hidden=True) -> None:
+ name = autostart_win.task_name(user)
+ previous = autostart_win._task_root(name, run)
+ preference = _read_preference()
+ if previous is None:
+ updated = ET.fromstring(autostart_win.task_xml(exe, user, run_level="LeastPrivilege"))
+ # The task can hold the privilege choice without opting the user into logon startup.
+ updated.find(NS + "Triggers/" + NS + "LogonTrigger/" + NS + "Enabled").text = "false"
+ else:
+ updated = copy.deepcopy(previous)
+ level = _checked_task(updated, exe, user)
+ level.text = "HighestAvailable" if value else "LeastPrivilege"
+ _register_task(name, updated, run)
+ try:
+ _write_preference(value)
+ if not hidden:
+ _launch_replacement(exe, value, config_path, hidden=False)
+ elif config_path is None:
+ _launch_replacement(exe, value)
+ else:
+ _launch_replacement(exe, value, config_path)
+ except Exception:
+ rollback_errors = []
+ try:
+ if previous is None:
+ result = run(["schtasks", "/delete", "/tn", name, "/f"])
+ if result.returncode:
+ raise OSError("Windows could not remove the incomplete Beamer sign-in task")
+ else:
+ _register_task(name, previous, run)
+ except Exception as rollback_error:
+ rollback_errors.append(rollback_error)
+ LOGGER.exception("Could not restore the administrator setting after a failed change")
+ try:
+ _restore_preference(preference)
+ except Exception as rollback_error:
+ rollback_errors.append(rollback_error)
+ LOGGER.exception("Could not restore the administrator preference after a failed change")
+ if rollback_errors:
+ raise OSError("Windows could not restore the previous administrator setting") from rollback_errors[0]
+ raise
+
+
+def _launch_unelevated(command: list[str]) -> None:
+ import pythoncom
+ from win32com.client import VARIANT, dynamic
+ from win32com.shell import shell, shellcon
+
+ pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
+ windows = desktop = provider = browser = view = background = application = None
+ try:
+ # The desktop view's Application lives in Explorer; creating Shell.Application
+ # directly can retain elevation. Raymond Chen's sequence and desktop finder:
+ # https://devblogs.microsoft.com/oldnewthing/20131118-00/?p=2643
+ # https://devblogs.microsoft.com/oldnewthing/20130318-00/?p=4933
+ try:
+ windows = dynamic.DumbDispatch(pythoncom.CoCreateInstance(
+ pythoncom.MakeIID("{9BA05972-F6A8-11CF-A442-00A0C90A8F39}"), None,
+ pythoncom.CLSCTX_LOCAL_SERVER, pythoncom.IID_IDispatch))
+ windows._FlagAsMethod("FindWindowSW")
+ desktop = windows.FindWindowSW(
+ VARIANT(pythoncom.VT_I4, shellcon.CSIDL_DESKTOP),
+ VARIANT(pythoncom.VT_EMPTY, None), 8,
+ VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I4, 0), 1)
+ if desktop is None:
+ raise DesktopShellUnavailable("Windows could not find this account's desktop shell")
+ provider = desktop._oleobj_.QueryInterface(pythoncom.IID_IServiceProvider)
+ browser = provider.QueryService(
+ pythoncom.MakeIID("{4C96BE40-915C-11CF-99D3-00AA004AE837}"), shell.IID_IShellBrowser)
+ view = browser.QueryActiveShellView()
+ background = dynamic.Dispatch(view.GetItemObject(shellcon.SVGIO_BACKGROUND, pythoncom.IID_IDispatch))
+ application = background.Application
+ except Exception as exc:
+ raise DesktopShellUnavailable("Windows could not find this account's desktop shell") from exc
+ # Windows applies this to the first ShowWindow, so 0 would hide a Settings window Qt shows.
+ show = 0 if "--hidden" in command else 1
+ application.ShellExecute(command[0], subprocess.list2cmdline(command[1:]), os.path.dirname(command[0]), "open", show)
+ finally:
+ application = background = view = browser = provider = desktop = windows = None
+ pythoncom.CoUninitialize()
+
+
+def _launch_replacement(exe: str, value: bool, config_path=None, *, hidden=True) -> int | None:
+ command = [exe, *(["--hidden"] if hidden else []), "--relaunched"]
+ if config_path is not None:
+ command.extend(["--config", os.path.abspath(str(config_path))])
+ if value:
+ environment = {**os.environ, "PYINSTALLER_RESET_ENVIRONMENT": "1"}
+ return subprocess.Popen(command, cwd=os.path.dirname(exe), creationflags=0x08000000, env=environment).pid
+ return _launch_unelevated(command)
+
+
+def run_helper(argv: list[str]) -> int:
+ hidden = not (argv and argv[-1] == "--show")
+ if not hidden:
+ argv = argv[:-1]
+ if (len(argv) not in (2, 4) or argv[0] not in ("--set-admin-mode", "--set-admin-startup")
+ or argv[1] not in ("on", "off")
+ or (not hidden and argv[0] == "--set-admin-startup")
+ or (len(argv) == 4 and (argv[0] == "--set-admin-startup" or argv[2] != "--config" or not os.path.isabs(argv[3])))):
+ return 1
+ try:
+ reason = unavailable_reason()
+ if reason:
+ raise OSError(reason)
+ import win32security
+ if not _token_information(win32security.TokenElevation):
+ raise OSError("Administrator setting changes require administrator permission")
+ exe = autostart_win.installed_exe()
+ autostart_win.migrate_legacy_task()
+ if argv[0] == "--set-admin-startup":
+ autostart_win.set_enabled(argv[1] == "on", exe, autostart_win.current_user())
+ return 0
+ config_path = argv[3] if len(argv) == 4 else None
+ if hidden:
+ _transition(argv[1] == "on", exe, autostart_win.current_user(), config_path=config_path)
+ else:
+ _transition(argv[1] == "on", exe, autostart_win.current_user(), config_path=config_path, hidden=False)
+ return 0
+ except DesktopShellUnavailable:
+ LOGGER.exception("Could not find the desktop shell for the administrator setting change")
+ return DESKTOP_SHELL_UNAVAILABLE
+ except Exception:
+ LOGGER.exception("Could not change the administrator setting")
+ return 1
diff --git a/win_app/autostart_win.py b/win_app/autostart_win.py
index 8b413ee..f2ccb52 100644
--- a/win_app/autostart_win.py
+++ b/win_app/autostart_win.py
@@ -1,8 +1,8 @@
"""Start at logon, owned by the app: each interactive account has its own scheduled task, so there
is no config field to disagree with it.
-The task uses the signed-in user's ordinary token, including standard accounts. The installer
-lowers old elevated tasks without changing whether the user enabled them.
+The task uses the signed-in user's ordinary token unless that administrator explicitly opts in
+on this PC. The installer lowers old elevated tasks when that preference is absent.
Registered from XML, not `schtasks /create /sc onlogon`: that form cannot set a working directory
and gives every task a 72-hour execution limit, which would stop Beamer three days after logon.
@@ -97,7 +97,15 @@ def installed_exe() -> Optional[str]:
return sys.executable if getattr(sys, "frozen", False) and not portable_runtime.enabled() else None
-def task_xml(exe: str, user: str, arguments: str = "--hidden") -> str:
+def preferred_run_level() -> str:
+ import admin_mode
+ return "HighestAvailable" if admin_mode.enabled() else "LeastPrivilege"
+
+
+def task_xml(exe: str, user: str, arguments: str = "--hidden", *, run_level: Optional[str] = None) -> str:
+ run_level = preferred_run_level() if run_level is None else run_level
+ if run_level not in ("LeastPrivilege", "HighestAvailable"):
+ raise ValueError("invalid Windows task run level")
return f"""<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<Triggers>
@@ -110,7 +118,7 @@ def task_xml(exe: str, user: str, arguments: str = "--hidden") -> str:
<Principal id="Author">
<UserId>{escape(user)}</UserId>
<LogonType>InteractiveToken</LogonType>
- <RunLevel>LeastPrivilege</RunLevel>
+ <RunLevel>{run_level}</RunLevel>
</Principal>
</Principals>
<Settings>
@@ -152,7 +160,10 @@ def _task_root(name: str, run: Runner):
def _task_enabled(name: str, run: Runner) -> bool:
root = _task_root(name, run)
ns = {"t": "http://schemas.microsoft.com/windows/2004/02/mit/task"}
- return root is not None and root.findtext("t:Settings/t:Enabled", "true", ns).lower() == "true"
+ return (root is not None
+ and root.findtext("t:Settings/t:Enabled", "true", ns).lower() == "true"
+ and any(trigger.findtext("t:Enabled", "true", ns).lower() == "true"
+ for trigger in root.findall("t:Triggers/t:LogonTrigger", ns)))
def _replacement_ready(root, exe: str, arguments: str) -> bool:
@@ -166,7 +177,7 @@ def _replacement_ready(root, exe: str, arguments: str) -> bool:
for trigger in root.findall("t:Triggers/t:LogonTrigger", ns))
and ntpath.normcase(command) == ntpath.normcase(exe)
and root.findtext("t:Actions/t:Exec/t:Arguments", "", ns) == arguments
- and root.findtext("t:Principals/t:Principal/t:RunLevel", "", ns) == "LeastPrivilege"
+ and root.findtext("t:Principals/t:Principal/t:RunLevel", "LeastPrivilege", ns) == preferred_run_level()
and root.findtext("t:Principals/t:Principal/t:LogonType", "", ns) == "InteractiveToken"
)
@@ -222,6 +233,13 @@ def set_enabled(enabled: bool, exe: str, user: Optional[str] = None, run: Runner
raise OSError("Portable Beamer cannot change start at sign-in")
user = user or current_user()
name = task_name(user)
+ if preferred_run_level() == "HighestAvailable":
+ import admin_mode
+ if not admin_mode._is_elevated():
+ if enabled and _replacement_ready(_task_root(name, run), exe, arguments):
+ return
+ admin_mode.change_startup(enabled)
+ return
if not enabled:
remove_legacy_task(run)
if run(["schtasks", "/query", "/tn", name]).returncode != 0:
@@ -230,6 +248,9 @@ def set_enabled(enabled: bool, exe: str, user: Optional[str] = None, run: Runner
else:
if not can_run_for_current_user():
raise OSError("Start at sign-in needs Beamer to run as the signed-in account")
+ if _replacement_ready(_task_root(name, run), exe, arguments):
+ remove_legacy_task(run, disable_first=True)
+ return
fd, path = tempfile.mkstemp(suffix=".xml")
try:
with os.fdopen(fd, "w", encoding="utf-16") as handle:
diff --git a/win_app/build.spec b/win_app/build.spec
index ebf349d..d5eb548 100644
--- a/win_app/build.spec
+++ b/win_app/build.spec
@@ -55,6 +55,6 @@ executable = EXE(
codesign_identity=None,
entitlements_file=None,
icon=str(source_dir / "Beamer.ico"),
- # Elevated targets remain protected by UIPI; installation owns maintenance privileges.
+ # Default launches stay ordinary; administrator control needs explicit per-PC consent.
uac_admin=False,
)
diff --git a/win_app/desktop_win.py b/win_app/desktop_win.py
index ce3218c..aab8ec1 100644
--- a/win_app/desktop_win.py
+++ b/win_app/desktop_win.py
@@ -108,31 +108,41 @@ def set_cursor_position_with_callback(x: int, y: int, on_placed=None, *, place_i
"""Report blocked placement without claiming that the receiver arrived."""
_require()
x, y = int(x), int(y)
+ error = None
def place():
+ nonlocal error
+ # Capture here: the ownership guard and foreground queries also call Win32.
+ ctypes.set_last_error(0)
if user32.SetCursorPos(x, y):
_refused_under[0] = None
if on_placed is not None:
on_placed()
return True
+ error = ctypes.get_last_error() or None
return False
# The warp and its completion share the receiver's ownership lock.
result = place_if_current(place) if place_if_current is not None else place()
if result is not False:
return
- error = ctypes.get_last_error()
import input_injector
- blocker = input_injector.foreground_class()
+ blocker = input_injector.foreground_blocker()
+ input_injector.report_input_problem(blocker, operation="SetCursorPos", error=error)
# A hold at the return edge lands here on every move, so once per blocker.
- if blocker != _refused_under[0]:
- _refused_under[0] = blocker
- input_injector.report_input_problem()
+ if blocker.key != _refused_under[0]:
+ _refused_under[0] = blocker.key
LOGGER.warning(
- "SetCursorPos refused (error %s) with %r in the foreground; Windows refuses Beamer's input "
- "while a window above its integrity level is in front, until a click on this PC",
- error, blocker,
+ "SetCursorPos refused (last_error=%s): process=%r pid=%s class=%r elevated=%s integrity=%s query_error=%s",
+ error, blocker.process_name, blocker.pid, blocker.window_class,
+ blocker.elevated, blocker.integrity, blocker.query_error,
)
+ def retry():
+ place_if_current(place)
+
+ if blocker.window_class == input_injector.GAMEINPUT_WINDOW_CLASS:
+ # Sender pins and return-edge corrections have no visit guard and can become stale.
+ input_injector.release_gameinput_foreground(after=retry if place_if_current is not None else None)
# What SHQueryUserNotificationState says while something owns the whole screen. 3 is a Direct3D
diff --git a/win_app/firewall_win.py b/win_app/firewall_win.py
index 5b266bb..e6d0e51 100644
--- a/win_app/firewall_win.py
+++ b/win_app/firewall_win.py
@@ -198,7 +198,11 @@ def advise(status: FirewallStatus) -> Advice:
pairing_udp = status.pairing_allowed and status.pairing_covered
pairing_tcp = status.pairing_tcp_allowed and status.pairing_tcp_covered
if status.error:
- return Advice(tr("Beamer could not read the Windows Firewall: {error}").format(error=status.error), tr("Check again"), "check")
+ if status.error == "permission-denied" and not status.elevated:
+ sentence = tr("Beamer cannot check Windows Firewall without administrator permission; run the Beamer installer again to repair its rules.")
+ else:
+ sentence = tr("Beamer could not check Windows Firewall. Check again; if the problem continues, run the Beamer installer again to repair its rules.")
+ return Advice(sentence, tr("Check again"), "check")
if status.blocked:
return Advice(
tr("Windows Firewall has a block rule affecting Beamer's input or pairing traffic; ask your administrator "
@@ -272,6 +276,7 @@ _RULES_FOR_LEAF = (
)
_STATUS_SCRIPT = _PREAMBLE + """
+try {{
$exe = {exe}
$rules = @()
foreach ($filter in $({filters})) {{
@@ -291,6 +296,28 @@ $networks = @(Get-NetConnectionProfile | ForEach-Object {{
}}
}})
[pscustomobject]@{{ rules = @($rules); networks = $networks }} | ConvertTo-Json -Depth 4 -Compress
+}} catch {{
+ $category = [int]$_.CategoryInfo.Category
+ $denied = $_.CategoryInfo.Category -eq [System.Management.Automation.ErrorCategory]::PermissionDenied
+ $hresult = $_.Exception.HResult
+ $nativeError = $null
+ for ($failure = $_.Exception; $null -ne $failure; $failure = $failure.InnerException) {{
+ if ($failure -is [Microsoft.Management.Infrastructure.CimException]) {{
+ $nativeError = [int]$failure.NativeErrorCode
+ if ($failure.NativeErrorCode -eq [Microsoft.Management.Infrastructure.NativeErrorCode]::AccessDenied) {{
+ $denied = $true
+ }}
+ }}
+ # E_ACCESSDENIED and WBEM_E_ACCESS_DENIED remain stable across display languages.
+ if ($failure -is [System.UnauthorizedAccessException] -or
+ $failure.HResult -eq -2147024891 -or $failure.HResult -eq -2147217405) {{
+ $denied = $true
+ $hresult = $failure.HResult
+ }}
+ }}
+ $kind = if ($denied) {{ 'permission-denied' }} else {{ 'query-failed' }}
+ [pscustomobject]@{{error=$kind; category=$category; hresult=$hresult; native_error=$nativeError}} | ConvertTo-Json -Compress
+}}
"""
# The same rule is reached more than once (by its program and again by its display name), and a
@@ -337,10 +364,15 @@ def status(exe: str, port: int) -> FirewallStatus:
elevated = is_elevated()
try:
raw = _powershell(_STATUS_SCRIPT.format(exe=_quote(exe), filters=_RULES_FOR_LEAF))
- return interpret(json.loads(raw), exe, port, elevated)
- except Exception as exc:
+ payload = json.loads(raw)
+ if "error" not in payload:
+ return interpret(payload, exe, port, elevated)
+ error = "permission-denied" if payload["error"] == "permission-denied" else "query-failed"
+ LOGGER.warning("Firewall status query failed: %s", payload)
+ except Exception:
LOGGER.exception("Firewall status failed")
- return FirewallStatus(port, False, False, (), (), False, (), elevated, error=str(exc) or type(exc).__name__)
+ error = "query-failed"
+ return FirewallStatus(port, False, False, (), (), False, (), elevated, error=error)
def repair(exe: str, port: int, profiles: Sequence[str] = ("Private",)) -> None:
diff --git a/win_app/input_blocker.py b/win_app/input_blocker.py
new file mode 100644
index 0000000..106cb92
--- /dev/null
+++ b/win_app/input_blocker.py
@@ -0,0 +1,180 @@
+"""Read-only diagnostics for the foreground window when Windows refuses input."""
+
+from __future__ import annotations
+
+import ctypes
+from dataclasses import dataclass
+import ntpath
+import sys
+
+from core.i18n import tr
+
+
+DWORD = ctypes.c_uint32
+BOOL = ctypes.c_int32
+HANDLE = ctypes.c_void_p
+PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
+TOKEN_QUERY = 0x0008
+TOKEN_ELEVATION = 20
+TOKEN_INTEGRITY_LEVEL = 25
+SECURITY_MANDATORY_SYSTEM_RID = 0x4000
+ERROR_INSUFFICIENT_BUFFER = 122
+ERROR_INVALID_DATA = 13
+GAMEINPUT_WINDOW_CLASS = "GameInputServiceWindow"
+
+
+class SID_AND_ATTRIBUTES(ctypes.Structure):
+ _fields_ = [("Sid", ctypes.c_void_p), ("Attributes", DWORD)]
+
+
+class TOKEN_MANDATORY_LABEL(ctypes.Structure):
+ _fields_ = [("Label", SID_AND_ATTRIBUTES)]
+
+
+def _configure_apis(user, kernel, security) -> None:
+ user.GetForegroundWindow.argtypes = []
+ user.GetForegroundWindow.restype = HANDLE
+ user.GetClassNameW.argtypes = [HANDLE, ctypes.c_wchar_p, ctypes.c_int]
+ user.GetClassNameW.restype = ctypes.c_int
+ user.GetWindowThreadProcessId.argtypes = [HANDLE, ctypes.POINTER(DWORD)]
+ user.GetWindowThreadProcessId.restype = DWORD
+ kernel.OpenProcess.argtypes = [DWORD, BOOL, DWORD]
+ kernel.OpenProcess.restype = HANDLE
+ kernel.QueryFullProcessImageNameW.argtypes = [HANDLE, DWORD, ctypes.c_wchar_p, ctypes.POINTER(DWORD)]
+ kernel.QueryFullProcessImageNameW.restype = BOOL
+ kernel.CloseHandle.argtypes = [HANDLE]
+ kernel.CloseHandle.restype = BOOL
+ security.OpenProcessToken.argtypes = [HANDLE, DWORD, ctypes.POINTER(HANDLE)]
+ security.OpenProcessToken.restype = BOOL
+ security.GetTokenInformation.argtypes = [HANDLE, ctypes.c_int, ctypes.c_void_p, DWORD, ctypes.POINTER(DWORD)]
+ security.GetTokenInformation.restype = BOOL
+ security.IsValidSid.argtypes = [ctypes.c_void_p]
+ security.IsValidSid.restype = BOOL
+ security.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p]
+ security.GetSidSubAuthorityCount.restype = ctypes.POINTER(ctypes.c_ubyte)
+ security.GetSidSubAuthority.argtypes = [ctypes.c_void_p, DWORD]
+ security.GetSidSubAuthority.restype = ctypes.POINTER(DWORD)
+
+
+user32 = kernel32 = advapi32 = None
+if sys.platform == "win32":
+ try:
+ user32 = ctypes.WinDLL("user32", use_last_error=True)
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
+ _configure_apis(user32, kernel32, advapi32)
+ except (OSError, AttributeError):
+ user32 = kernel32 = advapi32 = None
+
+
+@dataclass(frozen=True)
+class ForegroundBlocker:
+ hwnd: int = 0
+ pid: int = 0
+ window_class: str = ""
+ process_name: str = ""
+ elevated: bool | None = None
+ integrity: int | None = None
+ query_error: int | None = None
+
+ @property
+ def key(self) -> tuple[int, int, str]:
+ return self.pid, self.hwnd, self.window_class
+
+ def message(self, *, receiver_elevated: bool = False) -> str:
+ app = self.process_name or self.window_class or tr("the foreground window")
+ if self.window_class == GAMEINPUT_WINDOW_CLASS:
+ return tr("Windows blocked Beamer's input because {app} is GameInput's system window. Click a normal window on this PC to continue.").format(app=app)
+ if self.integrity is not None and self.integrity >= SECURITY_MANDATORY_SYSTEM_RID:
+ return tr("Windows blocked Beamer's input because {app} is a system-level window. Use it locally and click a normal window on this PC to continue.").format(app=app)
+ if self.elevated is True and not receiver_elevated:
+ return tr("Windows blocked Beamer's input because {app} is running as administrator. Click a normal window on this PC to continue.").format(app=app)
+ if self.query_error is not None:
+ return tr("Windows blocked Beamer's input while {app} was in front. Windows did not allow Beamer to inspect this window's process. Click a normal window on this PC to continue.").format(app=app)
+ return tr("Windows blocked Beamer's input while {app} was in front. Click a normal window on this PC to continue.").format(app=app)
+
+
+def _last_error() -> int:
+ return ctypes.get_last_error()
+
+
+def _integrity_level(token) -> tuple[int | None, int | None]:
+ size = DWORD()
+ if not advapi32.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, None, 0, ctypes.byref(size)):
+ error = _last_error()
+ if error != ERROR_INSUFFICIENT_BUFFER:
+ return None, error
+ if size.value < ctypes.sizeof(TOKEN_MANDATORY_LABEL):
+ return None, ERROR_INVALID_DATA
+ buffer = ctypes.create_string_buffer(size.value)
+ capacity = size.value
+ if not advapi32.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, buffer, capacity, ctypes.byref(size)):
+ return None, _last_error()
+ if not ctypes.sizeof(TOKEN_MANDATORY_LABEL) <= size.value <= capacity:
+ return None, ERROR_INVALID_DATA
+ sid = ctypes.cast(buffer, ctypes.POINTER(TOKEN_MANDATORY_LABEL)).contents.Label.Sid
+ if not sid or not advapi32.IsValidSid(sid):
+ return None, ERROR_INVALID_DATA
+ count = advapi32.GetSidSubAuthorityCount(sid)
+ if not count or not count[0]:
+ return None, ERROR_INVALID_DATA
+ rid = advapi32.GetSidSubAuthority(sid, count[0] - 1)
+ return (int(rid[0]), None) if rid else (None, ERROR_INVALID_DATA)
+
+
+def foreground_blocker() -> ForegroundBlocker:
+ """Keep inaccessible processes uncertain; access denial alone does not prove elevation."""
+ if user32 is None or kernel32 is None or advapi32 is None:
+ return ForegroundBlocker()
+ values = {}
+ process = None
+ token = HANDLE()
+ try:
+ hwnd = user32.GetForegroundWindow()
+ if not hwnd:
+ return ForegroundBlocker()
+ values["hwnd"] = int(hwnd)
+ window_class = ctypes.create_unicode_buffer(256)
+ if user32.GetClassNameW(hwnd, window_class, len(window_class)):
+ values["window_class"] = window_class.value
+ else:
+ values["query_error"] = _last_error()
+ pid = DWORD()
+ if not user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) or not pid.value:
+ values.setdefault("query_error", _last_error())
+ return ForegroundBlocker(**values)
+ values["pid"] = pid.value
+ process = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid.value)
+ if not process:
+ values.setdefault("query_error", _last_error())
+ return ForegroundBlocker(**values)
+ image = ctypes.create_unicode_buffer(32768)
+ size = DWORD(len(image))
+ if kernel32.QueryFullProcessImageNameW(process, 0, image, ctypes.byref(size)):
+ values["process_name"] = ntpath.basename(image.value)
+ else:
+ values.setdefault("query_error", _last_error())
+ if not advapi32.OpenProcessToken(process, TOKEN_QUERY, ctypes.byref(token)):
+ values.setdefault("query_error", _last_error())
+ return ForegroundBlocker(**values)
+ elevation = DWORD()
+ size = DWORD()
+ if advapi32.GetTokenInformation(token.value, TOKEN_ELEVATION, ctypes.byref(elevation),
+ ctypes.sizeof(elevation), ctypes.byref(size)):
+ if size.value == ctypes.sizeof(elevation):
+ values["elevated"] = bool(elevation.value)
+ else:
+ values.setdefault("query_error", ERROR_INVALID_DATA)
+ else:
+ values.setdefault("query_error", _last_error())
+ values["integrity"], error = _integrity_level(token.value)
+ if error is not None:
+ values.setdefault("query_error", error)
+ except OSError as exc:
+ values.setdefault("query_error", getattr(exc, "winerror", None) or exc.errno or _last_error())
+ finally:
+ if token.value:
+ kernel32.CloseHandle(token.value)
+ if process:
+ kernel32.CloseHandle(process)
+ return ForegroundBlocker(**values)
diff --git a/win_app/input_injector.py b/win_app/input_injector.py
index fb07059..4543351 100644
--- a/win_app/input_injector.py
+++ b/win_app/input_injector.py
@@ -3,6 +3,8 @@
import ctypes
import functools
import logging
+import os
+import subprocess
import sys
import threading
import time
@@ -10,20 +12,38 @@ import unicodedata
from typing import Callable, Dict, List, Optional, Set, Tuple
from core.keytable import EVDEV_US
-from core.i18n import tr
+from input_blocker import foreground_blocker
+from firewall_win import is_elevated
LOGGER = logging.getLogger(__name__)
on_problem = None
_problem_at = float("-inf")
-
-
-def report_input_problem() -> None:
- global _problem_at
- now = time.monotonic()
- if on_problem is not None and now - _problem_at >= 30:
- _problem_at = now
- on_problem(tr("Windows blocked Beamer's input; use administrator windows locally and click a normal window on this PC to continue."))
+_problem_logged = None
+_problem_notified = set()
+_problem_lock = threading.Lock()
+
+
+def report_input_problem(blocker=None, *, operation="input", error=None) -> None:
+ global _problem_at, _problem_logged
+ blocker = blocker if blocker is not None else foreground_blocker()
+ with _problem_lock:
+ log_problem = blocker.key != _problem_logged
+ _problem_logged = blocker.key
+ now = time.monotonic()
+ notify = on_problem if (on_problem is not None and blocker.key not in _problem_notified
+ and now - _problem_at >= 30) else None
+ if notify is not None:
+ _problem_at = now
+ _problem_notified.add(blocker.key)
+ if log_problem:
+ LOGGER.warning(
+ "%s refused (last_error=%s): process=%r pid=%s class=%r elevated=%s integrity=%s query_error=%s",
+ operation, error, blocker.process_name, blocker.pid, blocker.window_class,
+ blocker.elevated, blocker.integrity, blocker.query_error,
+ )
+ if notify is not None:
+ notify(blocker.message(receiver_elevated=is_elevated()))
_IS_WINDOWS = sys.platform == "win32"
@@ -117,11 +137,15 @@ def _send_input(*inputs: INPUT) -> None:
raise RuntimeError("Win32 SendInput is only available on Windows")
count = len(inputs)
array = (INPUT * count)(*inputs)
+ ctypes.set_last_error(0)
sent = user32.SendInput(count, array, ctypes.sizeof(INPUT))
if sent != count:
- error = ctypes.get_last_error()
- report_input_problem()
- raise OSError(error, "Windows refused Beamer's input (administrator windows require local input)")
+ error = ctypes.get_last_error() or None
+ blocker = foreground_blocker()
+ report_input_problem(blocker, operation="SendInput", error=error)
+ if blocker.window_class == GAMEINPUT_WINDOW_CLASS:
+ release_gameinput_foreground()
+ raise OSError(error or 0, "Windows refused Beamer's input")
def _vk_key_scan(ch: str) -> int:
@@ -485,9 +509,14 @@ def inject_mouse_move(dx: int, dy: int) -> None:
watch_foreground()
-# GameInput can leave a SYSTEM-owned window in front; only local input can leave it.
+# GameInput can leave a SYSTEM-owned window in front after another window closes.
GAMEINPUT_WINDOW_CLASS = "GameInputServiceWindow"
+GAMEINPUT_RECOVERY_TASK = "Beamer-GameInputRecovery"
_seen_foreground = [None]
+_gameinput_lock = threading.Lock()
+_gameinput_restarted_at = float("-inf")
+_gameinput_running = False
+_gameinput_afters = []
def _window_class(hwnd) -> str:
@@ -515,10 +544,75 @@ def watch_foreground() -> None:
def release_gameinput_foreground(after: Optional[Callable[[], None]] = None) -> bool:
- """Report the SYSTEM-window limitation; service recovery belongs to installation."""
- if foreground_class() == GAMEINPUT_WINDOW_CLASS:
- report_input_problem()
- return False
+ """Request the installer's fixed SYSTEM task without elevating the input process."""
+ global _gameinput_restarted_at, _gameinput_running, _gameinput_afters
+ if foreground_class() != GAMEINPUT_WINDOW_CLASS:
+ return False
+ report_input_problem()
+ with _gameinput_lock:
+ if _gameinput_running:
+ if after is not None:
+ _gameinput_afters.append(after)
+ return True
+ now = time.monotonic()
+ if now - _gameinput_restarted_at < 60:
+ return False
+ _gameinput_restarted_at = now
+ _gameinput_running = True
+ _gameinput_afters = [after] if after is not None else []
+
+ def recover():
+ global _gameinput_running, _gameinput_afters
+ finished = False
+ try:
+ # Never resolve a privileged helper through the current directory or PATH.
+ system = ctypes.create_unicode_buffer(32768)
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
+ if not kernel.GetSystemDirectoryW(system, len(system)):
+ raise ctypes.WinError(ctypes.get_last_error())
+ completed = subprocess.run(
+ [os.path.join(system.value, "schtasks.exe"), "/Run", "/TN", GAMEINPUT_RECOVERY_TASK],
+ capture_output=True, timeout=10,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ if completed.returncode:
+ LOGGER.warning("GameInput recovery task could not start (exit %s); repair Beamer with its installer",
+ completed.returncode)
+ return
+ # /Run acknowledges dispatch, not completion. Only retry after the blocking window leaves.
+ for _ in range(100):
+ if foreground_class() != GAMEINPUT_WINDOW_CLASS:
+ with _gameinput_lock:
+ callbacks = _gameinput_afters
+ _gameinput_afters = []
+ _gameinput_running = False
+ finished = True
+ LOGGER.info("GameInput foreground released after recovery task")
+ # Different link threads can register out of visit order; each callback owns its guard.
+ for callback in callbacks:
+ try:
+ callback()
+ except Exception:
+ LOGGER.exception("Could not place the pointer after GameInput recovery")
+ return
+ time.sleep(0.1)
+ LOGGER.warning("GameInput still holds foreground after recovery task; a local click is needed")
+ except Exception:
+ LOGGER.exception("GameInput recovery failed; a local click is needed")
+ finally:
+ if not finished:
+ with _gameinput_lock:
+ _gameinput_running = False
+ _gameinput_afters = []
+
+ try:
+ threading.Thread(target=recover, name="Beamer-gameinput", daemon=True).start()
+ except Exception:
+ with _gameinput_lock:
+ _gameinput_running = False
+ _gameinput_afters = []
+ raise
+ return True
BUTTON_DOWN_FLAGS = {
diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.py
index 501acc6..4b14af3 100644
--- a/win_app/kvm_bridge_win.py
+++ b/win_app/kvm_bridge_win.py
@@ -321,6 +321,7 @@ class StatusBridge(QObject):
# (method, edge, x, y): the pointer landed on this PC at desktop pixel (x, y).
arrived = Signal(str, str, float, float)
firewall = Signal(object)
+ admin_changed = Signal(object)
# A pairing this PC hosted finished and was stored: the new peer entry.
paired = Signal(object)
# A pairing this PC requested ended: (the entry stored or None, the error or None).
@@ -570,6 +571,7 @@ class WindowsApplication(QWidget):
self.bridge.local_pressure.connect(self._on_local_pressure)
self.bridge.arrived.connect(self._on_arrival)
self.bridge.firewall.connect(self._on_firewall)
+ self.bridge.admin_changed.connect(self._on_admin_mode_changed)
self.bridge.paired.connect(self._on_paired)
self.bridge.pair_finished.connect(self._on_pair_finished)
self.bridge.sending.connect(self._on_sending)
@@ -1350,9 +1352,7 @@ class WindowsApplication(QWidget):
"edge, so the edges are never held for one and a drag can cross."), "note", wrap=True)
module.body.addWidget(self.wayland_crossing_note)
if sys.platform == "win32":
- module.body.addWidget(widgets.label(
- tr("Beamer controls normal windows; use administrator windows and Windows permission prompts locally."),
- "note", wrap=True))
+ self._admin_control(module)
for widget in (self.hold_switch, own_note, hold_note):
widget.setVisible(not platform_parts.WAYLAND)
# Wayland owns hiding during capture; it offers no global idle-pointer hide.
@@ -1361,6 +1361,65 @@ class WindowsApplication(QWidget):
self.wayland_crossing_note.setVisible(platform_parts.WAYLAND)
return module
+ def _admin_control(self, module) -> None:
+ self.admin_switch = widgets.Switch(tr("Control administrator windows"))
+ self.admin_switch.setFont(theme.font(theme.TYPE["body"]))
+ self.admin_switch.toggled.connect(self._set_admin_mode)
+ module.body.addWidget(self.admin_switch)
+ self.admin_note = widgets.label("", "note", wrap=True)
+ module.body.addWidget(self.admin_note)
+ module.body.addWidget(widgets.label(
+ tr("Use Windows permission prompts locally."), "note", wrap=True))
+ self._refresh_admin_mode()
+
+ def _refresh_admin_mode(self) -> None:
+ import admin_mode
+ try:
+ self._admin_mode_enabled = admin_mode.enabled()
+ reason = admin_mode.unavailable_reason()
+ except OSError:
+ self._admin_mode_enabled = False
+ reason = tr("Beamer could not read this PC's administrator setting. Restart Beamer to try again.")
+ self.admin_switch.blockSignals(True)
+ self.admin_switch.setChecked(self._admin_mode_enabled)
+ self.admin_switch.blockSignals(False)
+ self.admin_switch.setEnabled(not reason)
+ self.admin_note.setText(reason or tr(
+ "Beamer will run as administrator on this PC. Changing this restarts Beamer; Windows may ask for permission."))
+
+ def _set_admin_mode(self, enabled: bool) -> None:
+ import admin_mode
+ self.admin_switch.blockSignals(True)
+ self.admin_switch.setChecked(self._admin_mode_enabled)
+ self.admin_switch.blockSignals(False)
+ self.admin_switch.setEnabled(False)
+ self.admin_note.setText(tr("Waiting for Windows permission…"))
+
+ def work():
+ result = None
+ try:
+ if not admin_mode.change(enabled, config_path=self.config_path):
+ result = False
+ except Exception as exc:
+ LOGGER.exception("Could not change administrator mode")
+ result = exc
+ self.bridge.admin_changed.emit(result)
+
+ threading.Thread(target=work, name="Beamer-administrator", daemon=True).start()
+
+ def _on_admin_mode_changed(self, error) -> None:
+ if error is False:
+ self._refresh_admin_mode()
+ return
+ if error is None:
+ self.quit()
+ return
+ self.admin_switch.blockSignals(True)
+ self.admin_switch.setChecked(self._admin_mode_enabled)
+ self.admin_switch.blockSignals(False)
+ self.admin_switch.setEnabled(True)
+ self.admin_note.setText(str(error))
+
def _redirect_text(self) -> str:
"""Names the machine the button sends input to, which is the one the shortcut would pick."""
target = self.sender.shortcut_target()
@@ -5791,8 +5850,13 @@ def _claim_instance():
# and 183 (already exists) is the whole single-instance check.
kernel32 = _windows_kernel32()
mutex = kernel32.CreateMutexW(None, False, "Local\\Beamer.Receiver" + portable_runtime.instance_suffix())
- already_running = ctypes.get_last_error() == 183
+ error = ctypes.get_last_error()
+ already_running = error == 183
if not mutex:
+ # A medium replacement cannot open the high instance's mutex with all-access.
+ # Treat it as occupied so --relaunched waits until the old process has quit.
+ if error == 5:
+ return None
raise OSError("Beamer could not create its single-instance lock")
if already_running:
kernel32.CloseHandle(mutex)
@@ -5918,6 +5982,18 @@ def main() -> None:
if release is None:
activate_existing_instance(arguments.hidden, os.environ.get("XDG_ACTIVATION_TOKEN"))
return
+ startup_admin_error = None
+ if sys.platform == "win32":
+ import admin_mode
+ try:
+ relaunched_as_admin = admin_mode.relaunch_if_required(
+ arguments.config.expanduser().resolve(), hidden=arguments.hidden)
+ except OSError as exc:
+ startup_admin_error = exc
+ else:
+ if relaunched_as_admin:
+ release()
+ return
log_path = configure_logging()
if log_path is not None:
crash_log.install(log_path.parent, LOGGER)
@@ -5959,6 +6035,8 @@ def main() -> None:
)
application._input_controller_release = controller_release
controller_release = None
+ if startup_admin_error is not None:
+ application._on_admin_mode_changed(startup_admin_error)
quit_signals = quit_signals_module.QuitSignals(application.quit, parent=app)
instance_signal = InstanceSignal(application.show_window, parent=app)
if not instance_signal.listening:
@@ -6051,6 +6129,9 @@ def cleanup_for_uninstall() -> int:
if __name__ == "__main__":
+ if sys.platform == "win32" and sys.argv[1:2] in (["--set-admin-mode"], ["--set-admin-startup"]):
+ import admin_mode
+ sys.exit(admin_mode.run_helper(sys.argv[1:]))
# Before the single-instance lock, so a Beamer already running does not turn the probe away.
if sys.argv[1:2] == ["--import-probe"]:
sys.exit(import_probe(sys.argv[2], sys.argv[3:]))
diff --git a/win_app/tests/test_admin_mode.py b/win_app/tests/test_admin_mode.py
new file mode 100644
index 0000000..0f2caf1
--- /dev/null
+++ b/win_app/tests/test_admin_mode.py
@@ -0,0 +1,435 @@
+import subprocess
+import unittest
+import xml.etree.ElementTree as ET
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+import admin_mode
+import autostart_win
+
+
+EXE = r"C:\Beamer\Beamer.exe"
+USER = r"PC\owner"
+
+
+class AdminModeTests(unittest.TestCase):
+ def setUp(self):
+ token_launcher = patch("win32api.OpenProcess", side_effect=AssertionError("Token-based launch is forbidden"))
+ token_launcher.start()
+ self.addCleanup(token_launcher.stop)
+
+ def test_unelevated_launch_uses_desktop_view_application_and_preserves_arguments(self):
+ import pythoncom
+ from win32com.client import dynamic
+ from win32com.shell import shell, shellcon
+
+ desktop = Mock()
+ provider = desktop._oleobj_.QueryInterface.return_value
+ browser = provider.QueryService.return_value
+ view = browser.QueryActiveShellView.return_value
+ background = view.GetItemObject.return_value
+ windows = Mock()
+ command = [EXE, "--hidden", "--relaunched", "--config", r"C:\A & B\owner's settings.json"]
+
+ def find(location, root, window_class, hwnd, options):
+ self.assertEqual((location.varianttype, location.value), (pythoncom.VT_I4, 0))
+ self.assertEqual(root.varianttype, pythoncom.VT_EMPTY)
+ self.assertEqual((window_class, options), (8, 1))
+ self.assertEqual(hwnd.varianttype, pythoncom.VT_BYREF | pythoncom.VT_I4)
+ hwnd.value = 123
+ return desktop
+
+ windows.FindWindowSW.side_effect = find
+ with patch.object(pythoncom, "CoInitializeEx") as initialise, \
+ patch.object(pythoncom, "CoUninitialize") as uninitialise, \
+ patch.object(pythoncom, "CoCreateInstance", return_value=windows) as create, \
+ patch.object(dynamic, "DumbDispatch", side_effect=lambda value: value), \
+ patch.object(dynamic, "Dispatch", side_effect=lambda value: value):
+ self.assertIsNone(admin_mode._launch_unelevated(command))
+ initialise.assert_called_once_with(pythoncom.COINIT_APARTMENTTHREADED)
+ uninitialise.assert_called_once_with()
+ create.assert_called_once_with(
+ pythoncom.MakeIID("{9BA05972-F6A8-11CF-A442-00A0C90A8F39}"), None,
+ pythoncom.CLSCTX_LOCAL_SERVER, pythoncom.IID_IDispatch)
+ desktop._oleobj_.QueryInterface.assert_called_once_with(pythoncom.IID_IServiceProvider)
+ provider.QueryService.assert_called_once_with(
+ pythoncom.MakeIID("{4C96BE40-915C-11CF-99D3-00AA004AE837}"), shell.IID_IShellBrowser)
+ view.GetItemObject.assert_called_once_with(shellcon.SVGIO_BACKGROUND, pythoncom.IID_IDispatch)
+ background.Application.ShellExecute.assert_called_once_with(
+ EXE, '--hidden --relaunched --config "C:\\A & B\\owner\'s settings.json"', r"C:\Beamer", "open", 0)
+
+ def test_visible_unelevated_launch_shows_its_window(self):
+ import pythoncom
+ from win32com.client import dynamic
+
+ desktop = Mock()
+ background = (desktop._oleobj_.QueryInterface.return_value.QueryService.return_value
+ .QueryActiveShellView.return_value.GetItemObject.return_value)
+ windows = Mock()
+
+ def find(location, root, window_class, hwnd, options):
+ hwnd.value = 123
+ return desktop
+
+ windows.FindWindowSW.side_effect = find
+ with patch.object(pythoncom, "CoInitializeEx"), patch.object(pythoncom, "CoUninitialize"), \
+ patch.object(pythoncom, "CoCreateInstance", return_value=windows), \
+ patch.object(dynamic, "DumbDispatch", side_effect=lambda value: value), \
+ patch.object(dynamic, "Dispatch", side_effect=lambda value: value):
+ admin_mode._launch_unelevated([EXE, "--relaunched"])
+ background.Application.ShellExecute.assert_called_once_with(EXE, "--relaunched", r"C:\Beamer", "open", 1)
+
+ def test_missing_desktop_refuses_launch_and_balances_com(self):
+ import pythoncom
+ from win32com.client import dynamic
+ windows = Mock()
+ windows.FindWindowSW.return_value = None
+ with patch.object(pythoncom, "CoInitializeEx"), \
+ patch.object(pythoncom, "CoUninitialize") as uninitialise, \
+ patch.object(pythoncom, "CoCreateInstance", return_value=windows), \
+ patch.object(dynamic, "DumbDispatch", side_effect=lambda value: value), \
+ patch.object(admin_mode.subprocess, "Popen") as direct_launch:
+ with self.assertRaisesRegex(OSError, "desktop shell"):
+ admin_mode._launch_unelevated([EXE, "--hidden"])
+ uninitialise.assert_called_once_with()
+ direct_launch.assert_not_called()
+
+ def test_shell_execution_failure_balances_com_without_another_launcher(self):
+ import pythoncom
+ from win32com.client import dynamic
+ windows, desktop = Mock(), Mock()
+ windows.FindWindowSW.return_value = desktop
+ provider = desktop._oleobj_.QueryInterface.return_value
+ view = provider.QueryService.return_value.QueryActiveShellView.return_value
+ application = view.GetItemObject.return_value.Application
+ application.ShellExecute.side_effect = OSError("shell launch refused")
+ with patch.object(pythoncom, "CoInitializeEx"), \
+ patch.object(pythoncom, "CoUninitialize") as uninitialise, \
+ patch.object(pythoncom, "CoCreateInstance", return_value=windows), \
+ patch.object(dynamic, "DumbDispatch", side_effect=lambda value: value), \
+ patch.object(dynamic, "Dispatch", side_effect=lambda value: value), \
+ patch.object(admin_mode.subprocess, "Popen") as direct_launch:
+ with self.assertRaisesRegex(OSError, "shell launch refused"):
+ admin_mode._launch_unelevated([EXE])
+ uninitialise.assert_called_once_with()
+ direct_launch.assert_not_called()
+
+ def test_failed_com_initialisation_is_not_uninitialised(self):
+ import pythoncom
+ with patch.object(pythoncom, "CoInitializeEx", side_effect=OSError("COM unavailable")), \
+ patch.object(pythoncom, "CoUninitialize") as uninitialise:
+ with self.assertRaises(OSError):
+ admin_mode._launch_unelevated([EXE])
+ uninitialise.assert_not_called()
+
+ def test_shell_unavailable_helper_result_reaches_the_setting_reason(self):
+ import pythoncom
+ import win32api
+ import win32event
+ import win32process
+ from win32com.shell import shell
+ process = Mock()
+ with patch.object(pythoncom, "CoInitializeEx") as initialise, \
+ patch.object(pythoncom, "CoUninitialize") as uninitialise, \
+ patch.object(shell, "ShellExecuteEx", return_value={"hProcess": process}), \
+ patch.object(win32event, "WaitForSingleObject"), \
+ patch.object(win32process, "GetExitCodeProcess", return_value=2), \
+ patch.object(win32api, "CloseHandle") as close:
+ with self.assertRaisesRegex(OSError, "desktop shell"):
+ admin_mode._run_elevated_helper(False)
+ close.assert_called_once_with(process)
+ initialise.assert_called_once_with(pythoncom.COINIT_APARTMENTTHREADED)
+ uninitialise.assert_called_once_with()
+
+ def test_declined_uac_balances_the_helper_worker_com_apartment(self):
+ import pythoncom
+ from win32com.shell import shell
+ with patch.object(pythoncom, "CoInitializeEx") as initialise, \
+ patch.object(pythoncom, "CoUninitialize") as uninitialise, \
+ patch.object(shell, "ShellExecuteEx", side_effect=OSError(1223, "cancelled")):
+ with self.assertRaises(OSError):
+ admin_mode._run_elevated_helper(True)
+ initialise.assert_called_once_with(pythoncom.COINIT_APARTMENTTHREADED)
+ uninitialise.assert_called_once_with()
+
+ def test_missing_shell_rolls_back_and_returns_its_distinct_helper_result(self):
+ import pythoncom
+ from win32com.client import dynamic
+ windows = Mock()
+ windows.FindWindowSW.return_value = None
+ original = autostart_win.task_xml(EXE, USER, run_level="HighestAvailable")
+ task = original
+
+ def runner(args):
+ nonlocal task
+ if args[1] == "/query":
+ return subprocess.CompletedProcess(args, 0, task, "")
+ if args[1] == "/create":
+ with open(args[args.index("/xml") + 1], encoding="utf-16") as handle:
+ task = handle.read()
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ transition = admin_mode._transition
+ with patch.object(pythoncom, "CoInitializeEx"), \
+ patch.object(pythoncom, "CoUninitialize"), \
+ patch.object(pythoncom, "CoCreateInstance", return_value=windows), \
+ patch.object(dynamic, "DumbDispatch", side_effect=lambda value: value), \
+ patch.object(admin_mode, "unavailable_reason", return_value=""), \
+ patch.object(admin_mode, "_token_information", return_value=True), \
+ patch.object(admin_mode, "_read_preference", return_value=(1, 4)), \
+ patch.object(admin_mode, "_write_preference"), \
+ patch.object(admin_mode, "_restore_preference") as restore, \
+ patch.object(autostart_win, "installed_exe", return_value=EXE), \
+ patch.object(autostart_win, "current_user", return_value=USER), \
+ patch.object(autostart_win, "migrate_legacy_task"), \
+ patch.object(admin_mode, "_transition", side_effect=lambda value, exe, user, **kwargs: transition(value, exe, user, runner, **kwargs)):
+ self.assertEqual(admin_mode.run_helper(["--set-admin-mode", "off"]), 2)
+ self.assertEqual(ET.tostring(ET.fromstring(task)), ET.tostring(ET.fromstring(original)))
+ restore.assert_called_once_with((1, 4))
+
+ def test_token_query_closes_non_context_manager_pyhandle(self):
+ import win32security
+ closed = []
+ token = SimpleNamespace(Close=lambda: closed.append(True))
+ with patch.object(win32security, "OpenProcessToken", return_value=token), \
+ patch.object(win32security, "GetTokenInformation", return_value=3):
+ self.assertEqual(admin_mode._token_information(win32security.TokenElevationType), 3)
+ self.assertEqual(closed, [True])
+
+ def test_task_xml_obeys_machine_local_preference(self):
+ for elevated, expected in ((False, "LeastPrivilege"), (True, "HighestAvailable")):
+ with self.subTest(elevated=elevated), patch.object(admin_mode, "enabled", return_value=elevated):
+ root = ET.fromstring(autostart_win.task_xml(EXE, USER))
+ self.assertEqual(root.findtext("{*}Principals/{*}Principal/{*}RunLevel"), expected)
+
+ def test_replacement_validation_obeys_machine_local_preference(self):
+ xml = autostart_win.task_xml(EXE, USER).replace("LeastPrivilege", "HighestAvailable")
+ with patch.object(admin_mode, "enabled", return_value=True):
+ self.assertTrue(autostart_win._replacement_ready(ET.fromstring(xml), EXE, "--hidden"))
+ with patch.object(admin_mode, "enabled", return_value=False):
+ self.assertFalse(autostart_win._replacement_ready(ET.fromstring(xml), EXE, "--hidden"))
+
+ def test_cancelled_uac_preserves_preference(self):
+ with patch.object(admin_mode, "unavailable_reason", return_value=""), \
+ patch.object(admin_mode, "enabled", return_value=False), \
+ patch.object(admin_mode, "_run_elevated_helper", side_effect=OSError(1223, "cancelled")), \
+ patch.object(admin_mode, "_write_preference") as write:
+ with self.assertRaises(OSError):
+ admin_mode.change(True)
+ write.assert_not_called()
+
+ def test_portable_and_source_builds_are_unavailable(self):
+ with patch.object(admin_mode.sys, "platform", "win32"), \
+ patch.object(admin_mode.autostart_win, "installed_exe", return_value=None):
+ self.assertTrue(admin_mode.unavailable_reason())
+
+ def test_standard_account_is_unavailable(self):
+ with patch.object(admin_mode.sys, "platform", "win32"), \
+ patch.object(admin_mode.autostart_win, "installed_exe", return_value=EXE), \
+ patch.object(admin_mode.autostart_win, "can_run_for_current_user", return_value=True), \
+ patch.object(admin_mode, "_administrator_account", return_value=False):
+ self.assertTrue(admin_mode.unavailable_reason())
+
+ def test_another_administrators_account_is_unavailable(self):
+ with patch.object(admin_mode.sys, "platform", "win32"), \
+ patch.object(admin_mode.autostart_win, "installed_exe", return_value=EXE), \
+ patch.object(admin_mode.autostart_win, "can_run_for_current_user", return_value=False), \
+ patch.object(admin_mode, "_administrator_account", return_value=True):
+ self.assertTrue(admin_mode.unavailable_reason())
+
+ def test_unsplit_administrator_token_is_unavailable(self):
+ with patch.object(admin_mode.sys, "platform", "win32"), \
+ patch.object(admin_mode.autostart_win, "installed_exe", return_value=EXE), \
+ patch.object(admin_mode.autostart_win, "can_run_for_current_user", return_value=True), \
+ patch.object(admin_mode, "_administrator_account", return_value=True), \
+ patch.object(admin_mode, "_token_information", return_value=1):
+ self.assertIn("User Account Control", admin_mode.unavailable_reason())
+
+ def test_helper_only_accepts_fixed_boolean_argument(self):
+ with patch.object(admin_mode, "_transition") as transition:
+ self.assertNotEqual(admin_mode.run_helper(["--set-admin-mode", "maybe"]), 0)
+ transition.assert_not_called()
+
+ def test_helper_rejects_relative_config_before_changing_anything(self):
+ with patch.object(admin_mode, "_transition") as transition:
+ self.assertNotEqual(admin_mode.run_helper(["--set-admin-mode", "on", "--config", "relative.json"]), 0)
+ transition.assert_not_called()
+
+ def test_unchanged_selection_does_not_request_relaunch(self):
+ with patch.object(admin_mode, "unavailable_reason", return_value=""), \
+ patch.object(admin_mode, "enabled", return_value=True), \
+ patch.object(admin_mode, "_run_elevated_helper") as helper:
+ self.assertFalse(admin_mode.change(True))
+ helper.assert_not_called()
+
+ def test_custom_config_is_forwarded_to_helper_without_reading_it(self):
+ config_path = r"C:\A & B\owner's settings.json"
+ with patch.object(admin_mode, "unavailable_reason", return_value=""), \
+ patch.object(admin_mode, "enabled", return_value=False), \
+ patch.object(admin_mode, "_run_elevated_helper") as helper:
+ self.assertTrue(admin_mode.change(True, config_path))
+ helper.assert_called_once_with(True, config_path, hidden=False)
+
+ def test_manual_medium_launch_honours_the_existing_preference(self):
+ with patch.object(admin_mode.sys, "platform", "win32"), \
+ patch.object(admin_mode, "enabled", return_value=True), \
+ patch.object(admin_mode, "unavailable_reason", return_value=""), \
+ patch.object(admin_mode, "_token_information", return_value=False), \
+ patch.object(admin_mode, "_run_elevated_helper") as helper:
+ self.assertTrue(admin_mode.relaunch_if_required(r"C:\Beamer\settings.json"))
+ helper.assert_called_once_with(True, r"C:\Beamer\settings.json")
+
+ def test_already_elevated_logon_start_does_not_prompt(self):
+ with patch.object(admin_mode.sys, "platform", "win32"), \
+ patch.object(admin_mode, "enabled", return_value=True), \
+ patch.object(admin_mode, "unavailable_reason", return_value=""), \
+ patch.object(admin_mode, "_token_information", return_value=True), \
+ patch.object(admin_mode, "_run_elevated_helper") as helper:
+ self.assertFalse(admin_mode.relaunch_if_required())
+ helper.assert_not_called()
+
+ def test_manual_visible_launch_preserves_requested_visibility(self):
+ with patch.object(admin_mode.sys, "platform", "win32"), \
+ patch.object(admin_mode, "enabled", return_value=True), \
+ patch.object(admin_mode, "unavailable_reason", return_value=""), \
+ patch.object(admin_mode, "_token_information", return_value=False), \
+ patch.object(admin_mode, "_run_elevated_helper") as helper:
+ self.assertTrue(admin_mode.relaunch_if_required(hidden=False))
+ helper.assert_called_once_with(True, None, hidden=False)
+
+ def test_replacement_visibility_matches_request(self):
+ for hidden in (False, True):
+ with self.subTest(hidden=hidden), patch.object(admin_mode.subprocess, "Popen") as launch:
+ admin_mode._launch_replacement(EXE, True, hidden=hidden)
+ self.assertEqual("--hidden" in launch.call_args.args[0], hidden)
+ self.assertIn("--relaunched", launch.call_args.args[0])
+
+ def test_elevated_replacement_gets_an_independent_pyinstaller_environment(self):
+ with patch.dict(admin_mode.os.environ, {"FW26B_PARENT_ENV": "kept"}, clear=True), \
+ patch.object(admin_mode.subprocess, "Popen") as launch:
+ admin_mode._launch_replacement(EXE, True)
+ self.assertEqual(dict(admin_mode.os.environ), {"FW26B_PARENT_ENV": "kept"})
+ self.assertEqual(launch.call_args.kwargs["env"], {
+ "FW26B_PARENT_ENV": "kept", "PYINSTALLER_RESET_ENVIRONMENT": "1"})
+
+ def test_startup_helper_rejects_show_argument(self):
+ with patch.object(admin_mode, "_transition") as transition:
+ self.assertNotEqual(admin_mode.run_helper(["--set-admin-startup", "on", "--show"]), 0)
+ transition.assert_not_called()
+
+
+class TransitionTests(unittest.TestCase):
+ def setUp(self):
+ self.task = autostart_win.task_xml(EXE, USER)
+ self.saved = []
+ self.pref = False
+
+ def runner(self, args):
+ if args[1] == "/query":
+ return subprocess.CompletedProcess(args, 0, self.task, "")
+ if args[1] == "/create":
+ with open(args[args.index("/xml") + 1], encoding="utf-16") as handle:
+ self.task = handle.read()
+ self.saved.append(self.task)
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ def test_success_changes_only_runlevel_and_launches_hidden_replacement(self):
+ with patch.object(admin_mode, "_read_preference", return_value=None), \
+ patch.object(admin_mode, "_write_preference") as write, \
+ patch.object(admin_mode, "_launch_replacement") as launch:
+ admin_mode._transition(True, EXE, USER, self.runner)
+ changed = ET.fromstring(self.task)
+ original = ET.fromstring(self.task.replace("HighestAvailable", "LeastPrivilege"))
+ self.assertEqual(changed.findtext("{*}Principals/{*}Principal/{*}RunLevel"), "HighestAvailable")
+ self.assertEqual(ET.tostring(original), ET.tostring(ET.fromstring(autostart_win.task_xml(EXE, USER))))
+ write.assert_called_once_with(True)
+ launch.assert_called_once_with(EXE, True)
+
+ def test_transition_accepts_the_omitted_default_runlevel(self):
+ for value, expected in ((False, "LeastPrivilege"), (True, "HighestAvailable")):
+ self.task = autostart_win.task_xml(EXE, USER, run_level="LeastPrivilege").replace(
+ "<RunLevel>LeastPrivilege</RunLevel>", "")
+ with self.subTest(value=value), \
+ patch.object(admin_mode, "_read_preference", return_value=None), \
+ patch.object(admin_mode, "_write_preference") as write, \
+ patch.object(admin_mode, "_launch_replacement") as launch:
+ admin_mode._transition(value, EXE, USER, self.runner)
+ self.assertEqual(ET.fromstring(self.task).findtext("{*}Principals/{*}Principal/{*}RunLevel"), expected)
+ write.assert_called_once_with(value)
+ launch.assert_called_once_with(EXE, value)
+
+ def test_failed_replacement_restores_task_and_absent_preference(self):
+ original = self.task
+ with patch.object(admin_mode, "_read_preference", return_value=None), \
+ patch.object(admin_mode, "_write_preference") as write, \
+ patch.object(admin_mode, "_restore_preference") as restore, \
+ patch.object(admin_mode, "_launch_replacement", side_effect=OSError("launch failed")):
+ with self.assertRaisesRegex(OSError, "launch failed"):
+ admin_mode._transition(True, EXE, USER, self.runner)
+ self.assertEqual(ET.tostring(ET.fromstring(self.task)), ET.tostring(ET.fromstring(original)))
+ restore.assert_called_once_with(None)
+
+ def test_disabled_startup_stays_disabled_when_admin_mode_changes(self):
+ self.task = self.task.replace("<Enabled>true</Enabled>", "<Enabled>false</Enabled>")
+ with patch.object(admin_mode, "_read_preference", return_value=None), \
+ patch.object(admin_mode, "_write_preference"), \
+ patch.object(admin_mode, "_launch_replacement"):
+ admin_mode._transition(True, EXE, USER, self.runner)
+ self.assertFalse(autostart_win._task_enabled(autostart_win.task_name(USER), self.runner))
+
+ def test_no_task_creates_only_disabled_logon_trigger(self):
+ self.task = None
+ runner = self.runner
+
+ def absent_until_create(args):
+ if args[1] == "/query" and self.task is None:
+ return subprocess.CompletedProcess(args, 1, "", "")
+ return runner(args)
+
+ with patch.object(admin_mode, "_read_preference", return_value=None), \
+ patch.object(admin_mode, "_write_preference"), \
+ patch.object(admin_mode, "_launch_replacement"):
+ admin_mode._transition(True, EXE, USER, absent_until_create)
+ self.assertFalse(autostart_win._task_enabled(autostart_win.task_name(USER), runner))
+ self.assertEqual(ET.fromstring(self.task).findtext("{*}Principals/{*}Principal/{*}RunLevel"), "HighestAvailable")
+
+ def test_task_failure_never_changes_preference_or_launches(self):
+ def refusal(args):
+ if args[1] == "/create":
+ return subprocess.CompletedProcess(args, 1, "", "Access denied")
+ return self.runner(args)
+
+ with patch.object(admin_mode, "_read_preference", return_value=None), \
+ patch.object(admin_mode, "_write_preference") as write, \
+ patch.object(admin_mode, "_launch_replacement") as launch:
+ with self.assertRaisesRegex(OSError, "Access denied"):
+ admin_mode._transition(True, EXE, USER, refusal)
+ write.assert_not_called()
+ launch.assert_not_called()
+
+ def test_unrelated_task_is_never_overwritten(self):
+ self.task = self.task.replace(EXE, r"C:\Other\Beamer.exe")
+ with patch.object(admin_mode, "_read_preference", return_value=None), \
+ patch.object(admin_mode, "_write_preference") as write:
+ with self.assertRaisesRegex(OSError, "installed app"):
+ admin_mode._transition(True, EXE, USER, self.runner)
+ self.assertEqual(self.saved, [])
+ write.assert_not_called()
+
+ def test_ordinary_upgrade_keeps_opted_in_task_without_registering_it_again(self):
+ self.task = self.task.replace("LeastPrivilege", "HighestAvailable")
+ with patch.object(admin_mode, "enabled", return_value=True), \
+ patch.object(autostart_win, "can_run_for_current_user", return_value=True):
+ autostart_win.set_enabled(True, EXE, USER, self.runner)
+ self.assertEqual(self.saved, [])
+
+ def test_medium_startup_update_requests_consent_without_relaunching(self):
+ for start_at_sign_in in (False, True):
+ with self.subTest(enabled=start_at_sign_in), \
+ patch.object(admin_mode, "enabled", return_value=True), \
+ patch.object(admin_mode, "_is_elevated", return_value=False), \
+ patch.object(admin_mode, "change_startup") as change:
+ autostart_win.set_enabled(start_at_sign_in, EXE, USER, self.runner)
+ change.assert_called_once_with(start_at_sign_in)
+ self.assertEqual(self.saved, [])
+
diff --git a/win_app/tests/test_admin_mode_ui.py b/win_app/tests/test_admin_mode_ui.py
new file mode 100644
index 0000000..0117646
--- /dev/null
+++ b/win_app/tests/test_admin_mode_ui.py
@@ -0,0 +1,120 @@
+"""Synthetic Input controls: no task registration or UAC prompts."""
+
+import ctypes
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout
+
+import firewall_win
+import input_injector
+import kvm_bridge_win as kvm
+import widgets
+from input_blocker import ForegroundBlocker
+
+
+class AdminControlTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.app = QApplication.instance() or QApplication([])
+
+ def make_control(self, enabled=False, reason=""):
+ import admin_mode
+ page = SimpleNamespace(
+ _set_admin_mode=Mock(),
+ _refresh_admin_mode=lambda: kvm.WindowsApplication._refresh_admin_mode(page),
+ )
+ host = QWidget()
+ self.addCleanup(host.deleteLater)
+ module = SimpleNamespace(body=QVBoxLayout(host))
+ with patch.object(admin_mode, "enabled", return_value=enabled), \
+ patch.object(admin_mode, "unavailable_reason", return_value=reason):
+ kvm.WindowsApplication._admin_control(page, module)
+ return page, host
+
+ def test_toggle_matches_existing_switch_and_defaults_off(self):
+ page, host = self.make_control()
+ self.assertIsInstance(page.admin_switch, widgets.Switch)
+ self.assertFalse(page.admin_switch.isChecked())
+ self.assertTrue(page.admin_switch.isEnabled())
+ self.assertEqual(page.admin_switch.text(), "Control administrator windows")
+ self.assertIn("this PC", page.admin_note.text())
+ host.resize(340, 200)
+ host.layout().activate()
+ self.assertLessEqual(page.admin_switch.geometry().right(), host.width())
+
+ def test_unavailable_account_or_portable_has_visible_reason(self):
+ for reason in ("Use an administrator account on this PC.", "Install Beamer to use this setting."):
+ page, _ = self.make_control(reason=reason)
+ self.assertFalse(page.admin_switch.isEnabled())
+ self.assertEqual(page.admin_note.text(), reason)
+
+ def test_cancelled_request_restores_toggle_without_quitting(self):
+ page, _ = self.make_control(enabled=False)
+ page.quit = Mock()
+ page.admin_switch.setChecked(True)
+ kvm.WindowsApplication._on_admin_mode_changed(page, OSError("Administrator permission was cancelled. Nothing changed."))
+ self.assertFalse(page.admin_switch.isChecked())
+ self.assertIn("cancelled", page.admin_note.text())
+ page.quit.assert_not_called()
+
+ def test_success_quits_only_after_helper_completes(self):
+ page, _ = self.make_control()
+ page.quit = Mock()
+ kvm.WindowsApplication._on_admin_mode_changed(page, None)
+ page.quit.assert_called_once_with()
+
+ def test_pending_request_keeps_old_state_and_passes_active_pairing_path(self):
+ import admin_mode
+ page, _ = self.make_control()
+ page.config_path = Path(r"C:\Synthetic Profile\settings.json")
+ page.bridge = SimpleNamespace(admin_changed=SimpleNamespace(emit=Mock()))
+ with patch.object(kvm.threading, "Thread") as thread, \
+ patch.object(admin_mode, "change", return_value=True) as change:
+ kvm.WindowsApplication._set_admin_mode(page, True)
+ self.assertFalse(page.admin_switch.isChecked())
+ self.assertFalse(page.admin_switch.isEnabled())
+ change.assert_not_called()
+ thread.call_args.kwargs["target"]()
+ change.assert_called_once_with(True, config_path=page.config_path)
+ page.bridge.admin_changed.emit.assert_called_once_with(None)
+
+ def test_no_change_does_not_quit_the_only_receiver(self):
+ page, _ = self.make_control()
+ page.quit = Mock()
+ page._refresh_admin_mode = Mock()
+ kvm.WindowsApplication._on_admin_mode_changed(page, False)
+ page.quit.assert_not_called()
+ page._refresh_admin_mode.assert_called_once_with()
+
+
+class ElevatedDiagnosticTests(unittest.TestCase):
+ def test_elevated_receiver_does_not_blame_equal_integrity_target(self):
+ blocker = ForegroundBlocker(process_name="admin.exe", elevated=True, integrity=0x3000)
+ notices = []
+ with patch.object(input_injector, "is_elevated", return_value=True, create=True), \
+ patch.object(input_injector, "on_problem", notices.append), \
+ patch.object(input_injector, "_problem_at", float("-inf")), \
+ patch.object(input_injector, "_problem_notified", set()):
+ input_injector.report_input_problem(blocker)
+ self.assertEqual(len(notices), 1)
+ self.assertNotIn("running as administrator", notices[0])
+ self.assertIn("admin.exe", notices[0])
+
+ def test_elevated_firewall_denial_does_not_ask_for_permission_it_has(self):
+ status = firewall_win.FirewallStatus(24820, False, False, (), (), False, (), True,
+ error="permission-denied")
+ self.assertNotIn("without administrator permission", firewall_win.advise(status).sentence)
+
+ def test_medium_replacement_waits_for_high_instance_mutex(self):
+ kernel = SimpleNamespace(CreateMutexW=Mock(return_value=None))
+ with patch.object(kvm.sys, "platform", "win32"), \
+ patch.object(kvm, "_windows_kernel32", return_value=kernel), \
+ patch.object(ctypes, "get_last_error", return_value=5, create=True):
+ self.assertIsNone(kvm._claim_instance())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_autostart_win.py b/win_app/tests/test_autostart_win.py
index 4dacc6b..1eee7d1 100644
--- a/win_app/tests/test_autostart_win.py
+++ b/win_app/tests/test_autostart_win.py
@@ -45,6 +45,14 @@ class TaskXmlTests(unittest.TestCase):
def test_escapes_the_path(self):
ET.fromstring(autostart_win.task_xml(r"C:\A & B\Beamer.exe", "u").replace('encoding="UTF-16"', ""))
+ def test_omitted_runlevel_matches_only_the_default_privilege_preference(self):
+ root = ET.fromstring(autostart_win.task_xml(EXE, r"STUDIO-PC\alex", run_level="LeastPrivilege").replace(
+ "<RunLevel>LeastPrivilege</RunLevel>", ""))
+ with patch.object(autostart_win, "preferred_run_level", return_value="LeastPrivilege"):
+ self.assertTrue(autostart_win._replacement_ready(root, EXE, "--hidden"))
+ with patch.object(autostart_win, "preferred_run_level", return_value="HighestAvailable"):
+ self.assertFalse(autostart_win._replacement_ready(root, EXE, "--hidden"))
+
class SwitchTests(unittest.TestCase):
def test_empty_session_identity_is_reported_as_unavailable(self):
diff --git a/win_app/tests/test_firewall_win.py b/win_app/tests/test_firewall_win.py
index 7c66edb..26b8264 100644
--- a/win_app/tests/test_firewall_win.py
+++ b/win_app/tests/test_firewall_win.py
@@ -5,6 +5,7 @@ the status script emits, so the decisions run on the Mac with no Windows at all.
"""
import unittest
+import json
import os
import sys
from unittest import mock
@@ -253,10 +254,52 @@ class InterpretTests(InstallerAdviceAssertions, unittest.TestCase):
self.assertIn("administrator", advice.sentence)
def test_error_offers_a_recheck(self):
- status = firewall_win.FirewallStatus(PORT, False, False, (), (), False, (), True, error="Access is denied")
+ status = firewall_win.FirewallStatus(PORT, False, False, (), (), False, (), True,
+ error="Get-NetFirewallApplicationFilter : Acceso denegado")
advice = advise(status)
self.assertEqual(advice.action, "check")
- self.assertIn("Access is denied", advice.sentence)
+ self.assertNotIn("Get-NetFirewall", advice.sentence)
+ self.assertNotIn("Acceso denegado", advice.sentence)
+
+ def test_permission_refusal_does_not_claim_missing_rules(self):
+ raw = json.dumps({"error": "permission-denied", "category": 18, "hresult": -2147024891})
+ with mock.patch.object(firewall_win, "is_elevated", return_value=False), \
+ mock.patch.object(firewall_win, "_powershell", return_value=raw):
+ status = firewall_win.status(EXE, PORT)
+ self.assertEqual(status.error, "permission-denied")
+ self.assertFalse(status.elevated)
+ self.assertFalse(status.allowed)
+ self.assertFalse(firewall_win.missing_rule(status))
+ advice = advise(status)
+ self.assertIn("administrator", advice.sentence)
+ self.assertIn("installer", advice.sentence)
+ self.assertNotIn("need attention", advice.sentence)
+ self.assertEqual(advice.action, "check")
+
+ def test_unexpected_status_errors_never_reach_the_advice(self):
+ failures = (RuntimeError("Get-NetFirewallApplicationFilter : Acceso denegado"),
+ TimeoutError("private PowerShell diagnostic"))
+ for failure in failures:
+ with self.subTest(failure=type(failure).__name__), \
+ mock.patch.object(firewall_win, "is_elevated", return_value=False), \
+ mock.patch.object(firewall_win, "_powershell", side_effect=failure):
+ status = firewall_win.status(EXE, PORT)
+ self.assertEqual(status.error, "query-failed")
+ self.assertFalse(firewall_win.missing_rule(status))
+ self.assertNotIn(str(failure), advise(status).sentence)
+
+ def test_structured_unexpected_failure_does_not_claim_missing_rules(self):
+ with mock.patch.object(firewall_win, "_powershell", return_value='{"error":"query-failed","category":0}'):
+ status = firewall_win.status(EXE, PORT)
+ self.assertEqual(status.error, "query-failed")
+ self.assertFalse(firewall_win.missing_rule(status))
+
+ def test_malformed_status_payload_does_not_claim_missing_rules(self):
+ for raw in ('{"error":"unrecognised diagnostic"}', '{"rules":[],"networks":[]} trailing'):
+ with self.subTest(raw=raw), mock.patch.object(firewall_win, "_powershell", return_value=raw):
+ status = firewall_win.status(EXE, PORT)
+ self.assertEqual(status.error, "query-failed")
+ self.assertFalse(firewall_win.missing_rule(status))
def test_status_off_windows_reports_an_error_not_a_crash(self):
if firewall_win._IS_WINDOWS:
@@ -266,6 +309,51 @@ class InterpretTests(InstallerAdviceAssertions, unittest.TestCase):
self.assertFalse(status.allowed)
[email protected](sys.platform == "win32", "native Windows PowerShell error records")
+class StatusErrorRecordTests(unittest.TestCase):
+ def test_cim_native_error_code_requires_a_typed_access_denied_exception(self):
+ for code, expected in ((2, "permission-denied"), (5, "query-failed")):
+ script = f"""
+$failure = [Microsoft.Management.Infrastructure.CimException]::new('Acceso denegado')
+$field = $failure.GetType().GetField('<NativeErrorCode>k__BackingField', 'Instance,NonPublic')
+$field.SetValue($failure, [Microsoft.Management.Infrastructure.NativeErrorCode]{code})
+$record = [System.Management.Automation.ErrorRecord]::new($failure, 'FW26CimFixture',
+ [System.Management.Automation.ErrorCategory]::InvalidOperation, $null)
+Write-Error -ErrorRecord $record
+"""
+ with self.subTest(code=code):
+ raw = firewall_win._powershell(firewall_win._STATUS_SCRIPT.format(
+ exe=firewall_win._quote(EXE), filters=script))
+ payload = json.loads(raw)
+ self.assertNotEqual(payload["category"], 18)
+ self.assertNotIn(payload["hresult"], (-2147024891, -2147217405))
+ self.assertEqual(payload["error"], expected)
+ self.assertEqual(payload["native_error"], code)
+
+ def test_localised_permission_category_is_classified_without_message_matching(self):
+ with mock.patch.object(firewall_win, "_RULES_FOR_LEAF", "Write-Error 'Acceso denegado' -Category PermissionDenied"), \
+ mock.patch.object(firewall_win, "is_elevated", return_value=False):
+ status = firewall_win.status(EXE, PORT)
+ self.assertEqual(status.error, "permission-denied")
+ self.assertIn("administrator", advise(status).sentence)
+ self.assertFalse(firewall_win.missing_rule(status))
+
+ def test_access_denied_hresult_is_classified_without_message_matching(self):
+ for hresult in (-2147024891, -2147217405):
+ with self.subTest(hresult=hresult), mock.patch.object(
+ firewall_win, "_RULES_FOR_LEAF",
+ f"throw [System.Runtime.InteropServices.COMException]::new('Refus', {hresult})",
+ ):
+ status = firewall_win.status(EXE, PORT)
+ self.assertEqual(status.error, "permission-denied")
+
+ def test_localised_access_words_alone_are_not_classified_as_permission(self):
+ with mock.patch.object(firewall_win, "_RULES_FOR_LEAF", "throw 'Acceso denegado'"):
+ status = firewall_win.status(EXE, PORT)
+ self.assertEqual(status.error, "query-failed")
+ self.assertNotIn("Acceso denegado", advise(status).sentence)
+
+
class RepairScriptTests(unittest.TestCase):
def test_repair_never_opens_the_port_on_public(self):
rendered = firewall_win._ADD_SCRIPT.format(
diff --git a/win_app/tests/test_gameinput_foreground.py b/win_app/tests/test_gameinput_foreground.py
index 937f01e..ce10590 100644
--- a/win_app/tests/test_gameinput_foreground.py
+++ b/win_app/tests/test_gameinput_foreground.py
@@ -1,9 +1,10 @@
-"""UIPI refusals are reported without runtime service recovery."""
+"""GameInput recovery delegates only a fixed installer-owned task."""
import ctypes
import os
import subprocess
import sys
+from types import SimpleNamespace
import unittest
from unittest import mock
@@ -11,6 +12,8 @@ sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(
import desktop_win
import input_injector
+from input_blocker import ForegroundBlocker
+from tests.test_input_blocker import LORBY_CLASSES
class FakeUser32:
@@ -47,38 +50,139 @@ class GameInputForegroundTests(unittest.TestCase):
mock.patch.object(ctypes, "get_last_error", create=True, return_value=0),
mock.patch.object(input_injector, "_seen_foreground", [None]),
mock.patch.object(input_injector, "_problem_at", float("-inf")),
+ mock.patch.object(input_injector, "_problem_notified", set(), create=True),
+ mock.patch.object(input_injector, "_problem_logged", None),
mock.patch.object(desktop_win, "_refused_under", [None]),
+ mock.patch.object(input_injector, "foreground_blocker", side_effect=lambda: ForegroundBlocker(
+ hwnd=self.user32.foreground or 0, pid=10,
+ window_class=self.user32.classes.get(self.user32.foreground, ""), process_name="test.exe")),
+ mock.patch.object(input_injector, "_gameinput_restarted_at", float("-inf")),
+ mock.patch.object(input_injector, "_gameinput_running", False),
+ mock.patch.object(input_injector, "_gameinput_afters", []),
]
for patch in patches:
patch.start()
self.addCleanup(patch.stop)
- def test_gameinput_foreground_reports_the_limit_without_restarting_a_service(self):
+ def test_gameinput_foreground_requests_recovery_off_the_input_thread(self):
self.user32.foreground = GAMEINPUT
notice = mock.Mock()
with mock.patch.object(input_injector, "on_problem", notice), \
mock.patch.object(subprocess, "run") as run, \
mock.patch.object(subprocess, "Popen") as popen, \
- mock.patch.object(os, "system") as system:
+ mock.patch.object(os, "system") as system, \
+ mock.patch.object(input_injector.threading, "Thread") as thread:
input_injector.watch_foreground()
notice.assert_called_once()
- self.assertIn("administrator windows locally", notice.call_args.args[0])
+ thread.return_value.start.assert_called_once()
run.assert_not_called()
popen.assert_not_called()
system.assert_not_called()
+ def test_recovery_retries_placement_only_while_visit_is_current(self):
+ self.user32.foreground = GAMEINPUT
+ self.user32.set_results = [0, 1]
+ callbacks = []
+ placed = mock.Mock()
+ current = [True]
+ with mock.patch.object(input_injector, "release_gameinput_foreground", side_effect=lambda after=None: callbacks.append(after) or True), \
+ mock.patch.object(input_injector, "report_input_problem"):
+ desktop_win.set_cursor_position_with_callback(10, 20, placed,
+ place_if_current=lambda action: action() if current[0] else None)
+ self.assertEqual(len(callbacks), 1)
+ current[0] = False
+ callbacks[0]()
+ self.assertEqual(self.user32.set_calls, [(10, 20)])
+ placed.assert_not_called()
+
+ def test_recovery_places_pointer_and_acknowledges_current_visit(self):
+ self.user32.foreground = GAMEINPUT
+ self.user32.set_results = [0, 1]
+ callbacks = []
+ placed = mock.Mock()
+ with mock.patch.object(input_injector, "release_gameinput_foreground", side_effect=lambda after=None: callbacks.append(after) or True), \
+ mock.patch.object(input_injector, "report_input_problem"):
+ desktop_win.set_cursor_position_with_callback(10, 20, placed,
+ place_if_current=lambda action: action())
+ self.assertEqual(len(callbacks), 1)
+ self.user32.foreground = EXPLORER
+ callbacks[0]()
+ self.assertEqual(self.user32.set_calls, [(10, 20), (10, 20)])
+ placed.assert_called_once_with()
+
+ def test_unguarded_sender_pin_cannot_warp_after_recovery(self):
+ self.user32.foreground = GAMEINPUT
+ self.user32.set_results = [0]
+ with mock.patch.object(input_injector, "release_gameinput_foreground") as recovery, \
+ mock.patch.object(input_injector, "report_input_problem"):
+ desktop_win.set_cursor_position(10, 20)
+ recovery.assert_called_once_with(after=None)
+
def test_input_problem_notice_is_throttled_for_thirty_seconds(self):
notices = []
with mock.patch.object(input_injector, "on_problem", notices.append):
input_injector.report_input_problem()
self.clock[0] += 29
+ self.user32.foreground = EXPLORER
input_injector.report_input_problem()
self.clock[0] += 1
input_injector.report_input_problem()
self.assertEqual(len(notices), 2)
- self.assertIn("click a normal window on this PC", notices[0])
+ self.assertIn("Click a normal window on this PC", notices[0])
+
+ def test_lorby_57_refusals_only_notify_once_for_each_of_three_instances(self):
+ notices = []
+ self.user32.set_results = [0] * 57
+ with mock.patch.object(input_injector, "on_problem", notices.append), \
+ mock.patch.object(desktop_win.LOGGER, "warning") as log:
+ for instance, window_class in enumerate(LORBY_CLASSES, start=1):
+ self.user32.foreground = instance
+ self.user32.classes[instance] = window_class
+ for _ in range(19):
+ self.clock[0] += 31
+ desktop_win.set_cursor_position(10, 20)
+ self.assertEqual(log.call_count, 3)
+ self.assertEqual(len(notices), 3)
+ # A successful placement or another blocker must not re-arm an old instance.
+ self.user32.foreground = 1
+ self.user32.set_results = [1, 0]
+ desktop_win.set_cursor_position(10, 20)
+ self.clock[0] += 31
+ desktop_win.set_cursor_position(10, 20)
+ input_injector.report_input_problem(operation="SendInput")
+ self.assertEqual(len(notices), 3)
+
+ def test_placement_discards_stale_error_and_captures_fresh_error_before_guard_returns(self):
+ for native_error in (0, 5):
+ with self.subTest(native_error=native_error):
+ last_error = [18]
+ def place(x, y):
+ self.assertEqual(last_error[0], 0)
+ last_error[0] = native_error
+ return 0
+ def guard(action):
+ result = action()
+ last_error[0] = 18
+ return result
+ desktop_win._refused_under[0] = None
+ with mock.patch.object(ctypes, "set_last_error", side_effect=lambda value: last_error.__setitem__(0, value)), \
+ mock.patch.object(ctypes, "get_last_error", side_effect=lambda: last_error[0]), \
+ mock.patch.object(self.user32, "SetCursorPos", side_effect=place), \
+ mock.patch.object(input_injector, "report_input_problem") as report:
+ desktop_win.set_cursor_position_with_callback(10, 20, place_if_current=guard)
+ self.assertEqual(report.call_args.kwargs["error"], native_error or None)
+
+ def test_sendinput_does_not_report_a_stale_last_error(self):
+ last_error = [18]
+ with mock.patch.object(ctypes, "set_last_error", side_effect=lambda value: last_error.__setitem__(0, value)), \
+ mock.patch.object(ctypes, "get_last_error", side_effect=lambda: last_error[0]), \
+ mock.patch.object(self.user32, "SendInput", create=True, return_value=0), \
+ mock.patch.object(input_injector, "report_input_problem") as report:
+ with self.assertRaises(OSError):
+ input_injector._send_input(input_injector.INPUT())
+ self.assertIsNone(report.call_args.kwargs["error"])
def test_ordinary_foreground_does_not_report_a_problem(self):
self.user32.foreground = EXPLORER
@@ -87,6 +191,77 @@ class GameInputForegroundTests(unittest.TestCase):
input_injector.watch_foreground()
notice.assert_not_called()
+ def test_recovery_is_rate_limited_and_keeps_guarded_placements(self):
+ self.user32.foreground = GAMEINPUT
+ first, latest = mock.Mock(), mock.Mock()
+ with mock.patch.object(input_injector.threading, "Thread") as thread, \
+ mock.patch.object(input_injector, "report_input_problem"):
+ self.assertTrue(input_injector.release_gameinput_foreground(first))
+ self.assertTrue(input_injector.release_gameinput_foreground(latest))
+ thread.assert_called_once()
+ self.assertEqual(input_injector._gameinput_afters, [first, latest])
+ input_injector._gameinput_running = False
+ self.clock[0] += 59
+ self.assertFalse(input_injector.release_gameinput_foreground())
+ self.clock[0] += 1
+ self.assertTrue(input_injector.release_gameinput_foreground())
+ self.assertEqual(thread.call_count, 2)
+
+ def _recovery_worker(self, after):
+ self.user32.foreground = GAMEINPUT
+ with mock.patch.object(input_injector.threading, "Thread") as thread, \
+ mock.patch.object(input_injector, "report_input_problem"):
+ self.assertTrue(input_injector.release_gameinput_foreground(after))
+ return thread.call_args.kwargs["target"]
+
+ def test_task_dispatch_is_fixed_hidden_and_waits_for_foreground_release(self):
+ placed = mock.Mock()
+ current_visit = [2]
+ worker = self._recovery_worker(lambda: placed() if current_visit[0] == 2 else None)
+ stale = mock.Mock()
+ # An older link can finish diagnostics after the current link has queued its placement.
+ input_injector.release_gameinput_foreground(after=lambda: stale() if current_visit[0] == 1 else None)
+ kernel = mock.Mock()
+ def system_directory(buffer, size):
+ buffer.value = r"C:\Windows\System32"
+ return len(buffer.value)
+ kernel.GetSystemDirectoryW.side_effect = system_directory
+ def release(_):
+ placed.assert_not_called()
+ self.user32.foreground = EXPLORER
+ with mock.patch.object(ctypes, "WinDLL", create=True, return_value=kernel), \
+ mock.patch.object(input_injector.subprocess, "run", return_value=SimpleNamespace(returncode=0)) as run, \
+ mock.patch.object(input_injector.time, "sleep", side_effect=release):
+ worker()
+ self.assertEqual(run.call_args.args[0], [os.path.join(r"C:\Windows\System32", "schtasks.exe"),
+ "/Run", "/TN", "Beamer-GameInputRecovery"])
+ self.assertEqual(run.call_args.kwargs["creationflags"], subprocess.CREATE_NO_WINDOW)
+ placed.assert_called_once_with()
+ stale.assert_not_called()
+ self.assertFalse(input_injector._gameinput_running)
+
+ def test_missing_task_or_stuck_foreground_never_acknowledges_arrival(self):
+ for returncode in (1, 0):
+ input_injector._gameinput_restarted_at = float("-inf")
+ placed = mock.Mock()
+ worker = self._recovery_worker(placed)
+ with mock.patch.object(ctypes, "WinDLL", create=True) as dll, \
+ mock.patch.object(input_injector.subprocess, "run", return_value=SimpleNamespace(returncode=returncode)), \
+ mock.patch.object(input_injector.time, "sleep"):
+ dll.return_value.GetSystemDirectoryW.return_value = 20
+ worker()
+ placed.assert_not_called()
+ self.assertFalse(input_injector._gameinput_running)
+
+ def test_sendinput_gameinput_refusal_starts_recovery(self):
+ self.user32.foreground = GAMEINPUT
+ with mock.patch.object(self.user32, "SendInput", create=True, return_value=0), \
+ mock.patch.object(input_injector, "release_gameinput_foreground") as recovery, \
+ mock.patch.object(input_injector, "report_input_problem"):
+ with self.assertRaises(OSError):
+ input_injector.inject_mouse_move(1, 2)
+ recovery.assert_called_once_with()
+
def test_successful_cursor_placement_runs_the_arrival_callback(self):
self.user32.foreground = EXPLORER
placed = mock.Mock()
@@ -103,13 +278,13 @@ class GameInputForegroundTests(unittest.TestCase):
self.user32.set_results = [0, 0, 1, 0]
placed = mock.Mock()
notice = mock.Mock()
- with mock.patch.object(input_injector, "report_input_problem", notice), \
+ with mock.patch.object(input_injector, "on_problem", notice), \
self.assertLogs(desktop_win.LOGGER, "WARNING") as logs:
for _ in range(4):
desktop_win.set_cursor_position_with_callback(10, 20, placed)
placed.assert_called_once_with()
- self.assertEqual(notice.call_count, 2)
+ self.assertEqual(notice.call_count, 1)
self.assertEqual(len(logs.records), 2)
self.assertIn("CabinetWClass", logs.output[0])
diff --git a/win_app/tests/test_input_blocker.py b/win_app/tests/test_input_blocker.py
new file mode 100644
index 0000000..8e901bd
--- /dev/null
+++ b/win_app/tests/test_input_blocker.py
@@ -0,0 +1,292 @@
+"""Foreground diagnostics never guess elevation from a refused process query."""
+
+import ctypes
+from dataclasses import FrozenInstanceError
+import os
+import sys
+import unittest
+from unittest import mock
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import input_blocker
+
+LORBY_CLASSES = (
+ "HwndWrapper[LorbyAxisAndOhs_MSFS2024.exe;;00000000-0000-4000-8000-000000000001]",
+ "HwndWrapper[LorbyAxisAndOhs_MSFS2024.exe;;00000000-0000-4000-8000-000000000002]",
+ "HwndWrapper[LorbyAxisAndOhs_MSFS2024.exe;;00000000-0000-4000-8000-000000000003]",
+)
+
+
+class NativeFixture:
+ HWND = 0x1234567887654321
+ PROCESS = 0x2345678998765432
+ TOKEN = 0x3456789AA9876543
+
+ def __init__(self):
+ self.user32 = mock.Mock()
+ self.kernel32 = mock.Mock()
+ self.advapi32 = mock.Mock()
+ self.error = 0
+ self.elevated = 1
+ self.integrity = 0x3000
+ self.failures = {}
+ self.window_class = "FlightSimulatorWindow"
+ self.image = r"C:\Games\PrivateFolder\FlightSimulator.exe"
+ self.user32.GetForegroundWindow.return_value = self.HWND
+ self.user32.GetClassNameW.side_effect = self.get_class
+ self.user32.GetWindowThreadProcessId.side_effect = self.get_pid
+ self.kernel32.OpenProcess.side_effect = self.open_process
+ self.kernel32.QueryFullProcessImageNameW.side_effect = self.get_image
+ self.advapi32.OpenProcessToken.side_effect = self.open_token
+ self.advapi32.GetTokenInformation.side_effect = self.get_token_information
+ self.advapi32.IsValidSid.return_value = 1
+ self.sid_count = ctypes.c_ubyte(1)
+ self.sid_rid = input_blocker.DWORD(self.integrity)
+ self.advapi32.GetSidSubAuthorityCount.return_value = ctypes.pointer(self.sid_count)
+ self.advapi32.GetSidSubAuthority.side_effect = self.get_rid
+ self.sid = ctypes.create_string_buffer(12)
+
+ def failed(self, operation):
+ if operation in self.failures:
+ self.error = self.failures[operation]
+ return True
+ return False
+
+ def get_class(self, hwnd, buffer, capacity):
+ buffer.value = self.window_class
+ return len(buffer.value)
+
+ def get_pid(self, hwnd, pid):
+ if self.failed("pid"):
+ return 0
+ ctypes.cast(pid, ctypes.POINTER(input_blocker.DWORD))[0] = 1234
+ return 5678
+
+ def open_process(self, access, inherit, pid):
+ return 0 if self.failed("process") else self.PROCESS
+
+ def get_image(self, process, flags, buffer, size):
+ if self.failed("image"):
+ return 0
+ buffer.value = self.image
+ ctypes.cast(size, ctypes.POINTER(input_blocker.DWORD))[0] = len(self.image)
+ return 1
+
+ def open_token(self, process, access, token):
+ if self.failed("token"):
+ return 0
+ ctypes.cast(token, ctypes.POINTER(ctypes.c_void_p))[0] = self.TOKEN
+ return 1
+
+ def get_token_information(self, token, kind, buffer, capacity, size):
+ size = ctypes.cast(size, ctypes.POINTER(input_blocker.DWORD))
+ if kind == 20:
+ if self.failed("elevation"):
+ return 0
+ ctypes.cast(buffer, ctypes.POINTER(input_blocker.DWORD))[0] = self.elevated
+ size[0] = 4
+ return 1
+ if self.failed("integrity"):
+ return 0
+ size[0] = ctypes.sizeof(input_blocker.TOKEN_MANDATORY_LABEL)
+ if buffer is None:
+ self.error = 122
+ return 0
+ if self.failed("integrity_data"):
+ return 0
+ label = ctypes.cast(buffer, ctypes.POINTER(input_blocker.TOKEN_MANDATORY_LABEL))
+ label.contents.Label.Sid = ctypes.addressof(self.sid)
+ return 1
+
+ def get_rid(self, sid, index):
+ self.sid_rid.value = self.integrity
+ return ctypes.pointer(self.sid_rid)
+
+
+class ForegroundBlockerTests(unittest.TestCase):
+ def test_lorby_wpf_classes_name_the_app_and_only_confirmed_elevation(self):
+ for window_class in LORBY_CLASSES:
+ for elevated in (True, False, None):
+ with self.subTest(window_class=window_class, elevated=elevated):
+ self.native.window_class = window_class
+ self.native.image = r"C:\Apps\LorbyAxisAndOhs_MSFS2024.exe"
+ self.native.elevated = bool(elevated)
+ self.native.failures = {"token": 5} if elevated is None else {}
+ result = input_blocker.foreground_blocker()
+ self.assertIn("LorbyAxisAndOhs_MSFS2024.exe", result.message())
+ self.assertNotIn("HwndWrapper", result.message())
+ self.assertEqual("running as administrator" in result.message(), elevated is True)
+ self.assertNotIn("GameInput", result.message())
+
+ def setUp(self):
+ self.native = NativeFixture()
+ for name in ("user32", "kernel32", "advapi32"):
+ patch = mock.patch.object(input_blocker, name, getattr(self.native, name))
+ patch.start()
+ self.addCleanup(patch.stop)
+ patch = mock.patch.object(ctypes, "get_last_error", create=True, side_effect=lambda: self.native.error)
+ patch.start()
+ self.addCleanup(patch.stop)
+
+ def test_snapshot_preserves_large_handles_and_only_the_process_basename(self):
+ result = input_blocker.foreground_blocker()
+ self.assertEqual(result.hwnd, 0x1234567887654321)
+ self.assertEqual(result.pid, 1234)
+ self.assertEqual(result.process_name, "FlightSimulator.exe")
+ self.assertEqual(result.key, (1234, 0x1234567887654321, "FlightSimulatorWindow"))
+ self.assertIs(result.elevated, True)
+ self.assertEqual(result.integrity, 0x3000)
+ self.assertIsNone(result.query_error)
+ self.native.kernel32.OpenProcess.assert_called_once_with(0x1000, False, 1234)
+ self.native.advapi32.OpenProcessToken.assert_called_once()
+ self.assertEqual(self.native.advapi32.OpenProcessToken.call_args.args[:2],
+ (0x2345678998765432, 0x0008))
+ self.assertEqual([call.args[0] for call in self.native.kernel32.CloseHandle.call_args_list],
+ [0x3456789AA9876543, 0x2345678998765432])
+ with self.assertRaises(FrozenInstanceError):
+ result.pid = 9
+
+ def test_access_denied_does_not_claim_administrator_or_system(self):
+ self.native.failures["process"] = 5
+ result = input_blocker.foreground_blocker()
+ self.assertIsNone(result.elevated)
+ self.assertIsNone(result.integrity)
+ self.assertEqual(result.query_error, 5)
+ self.assertIn("FlightSimulatorWindow", result.message())
+ self.assertNotIn("administrator", result.message())
+ self.assertNotIn("system-level", result.message())
+ self.native.kernel32.CloseHandle.assert_not_called()
+
+ def test_token_failure_keeps_the_named_process_and_closes_process(self):
+ self.native.failures["token"] = 5
+ result = input_blocker.foreground_blocker()
+ self.assertEqual(result.process_name, "FlightSimulator.exe")
+ self.assertIsNone(result.elevated)
+ self.assertEqual(result.query_error, 5)
+ self.native.kernel32.CloseHandle.assert_called_once_with(0x2345678998765432)
+
+ def test_image_failure_still_checks_the_token_and_uses_class_fallback(self):
+ self.native.failures["image"] = 299
+ result = input_blocker.foreground_blocker()
+ self.assertEqual(result.process_name, "")
+ self.assertIs(result.elevated, True)
+ self.assertEqual(result.integrity, 0x3000)
+ self.assertEqual(result.query_error, 299)
+ self.assertIn("FlightSimulatorWindow", result.message())
+ self.assertIn("administrator", result.message())
+
+ def test_elevation_failure_does_not_discard_confirmed_system_integrity(self):
+ self.native.failures["elevation"] = 5
+ self.native.integrity = 0x4000
+ result = input_blocker.foreground_blocker()
+ self.assertIsNone(result.elevated)
+ self.assertEqual(result.integrity, 0x4000)
+ self.assertEqual(result.query_error, 5)
+ self.assertIn("system-level", result.message())
+
+ def test_integrity_query_failures_close_both_handles_without_guessing(self):
+ for failure in ("integrity", "integrity_data"):
+ with self.subTest(failure=failure):
+ self.native.failures = {failure: 5}
+ self.native.kernel32.CloseHandle.reset_mock()
+ self.native.elevated = 0
+ result = input_blocker.foreground_blocker()
+ self.assertIs(result.elevated, False)
+ self.assertIsNone(result.integrity)
+ self.assertEqual(result.query_error, 5)
+ self.assertEqual(self.native.kernel32.CloseHandle.call_count, 2)
+
+ def test_invalid_integrity_sid_stays_unknown(self):
+ self.native.advapi32.IsValidSid.return_value = 0
+ result = input_blocker.foreground_blocker()
+ self.assertIsNone(result.integrity)
+ self.assertIsNotNone(result.query_error)
+ self.native.advapi32.GetSidSubAuthority.assert_not_called()
+ self.assertEqual(self.native.kernel32.CloseHandle.call_count, 2)
+
+ def test_zero_sid_subauthorities_never_reads_a_negative_index(self):
+ self.native.sid_count.value = 0
+ result = input_blocker.foreground_blocker()
+ self.assertIsNone(result.integrity)
+ self.native.advapi32.GetSidSubAuthority.assert_not_called()
+
+ def test_native_exception_still_closes_both_handles(self):
+ self.native.advapi32.GetTokenInformation.side_effect = OSError(6, "invalid handle")
+ result = input_blocker.foreground_blocker()
+ self.assertIsNone(result.elevated)
+ self.assertEqual(result.query_error, 6)
+ self.assertEqual(self.native.kernel32.CloseHandle.call_count, 2)
+
+ def test_process_id_failure_never_opens_an_unrelated_process(self):
+ self.native.failures["pid"] = 1400
+ result = input_blocker.foreground_blocker()
+ self.assertEqual(result.pid, 0)
+ self.assertEqual(result.query_error, 1400)
+ self.native.kernel32.OpenProcess.assert_not_called()
+
+ def test_missing_foreground_never_queries_a_process(self):
+ self.native.user32.GetForegroundWindow.return_value = 0
+ result = input_blocker.foreground_blocker()
+ self.assertEqual(result.key, (0, 0, ""))
+ self.assertIsNone(result.elevated)
+ self.native.kernel32.OpenProcess.assert_not_called()
+
+ def test_unavailable_win32_is_safe_unknown(self):
+ with mock.patch.object(input_blocker, "user32", None):
+ result = input_blocker.foreground_blocker()
+ self.assertEqual(result.key, (0, 0, ""))
+ self.assertIsNone(result.elevated)
+ self.assertIsNone(result.integrity)
+ self.assertIsNone(result.query_error)
+ self.assertIn("foreground window", result.message())
+
+ def test_messages_distinguish_gameinput_elevated_and_unknown(self):
+ cases = [
+ ({"window_class": "GameInputServiceWindow"}, "GameInput"),
+ ({"process_name": "admin.exe", "elevated": True}, "administrator"),
+ ({"process_name": "normal.exe", "elevated": False, "integrity": 0x2000}, "normal.exe"),
+ ({"window_class": "ProtectedWindow", "query_error": 5}, "ProtectedWindow"),
+ ]
+ for values, expected in cases:
+ with self.subTest(values=values):
+ self.assertIn(expected, input_blocker.ForegroundBlocker(**values).message())
+
+ def test_unknown_message_never_invents_elevation(self):
+ message = input_blocker.ForegroundBlocker(process_name="normal.exe", elevated=False,
+ integrity=0x2000).message()
+ self.assertIn("normal.exe", message)
+ self.assertNotIn("administrator", message)
+ self.assertNotIn("system-level", message)
+
+ def test_all_messages_translate_before_interpolating_process_name(self):
+ blocker = input_blocker.ForegroundBlocker(process_name="PrivateApp.exe", elevated=True)
+ seen = []
+ with mock.patch.object(input_blocker, "tr", side_effect=lambda template: seen.append(template) or template):
+ message = blocker.message()
+ self.assertIn("PrivateApp.exe", message)
+ self.assertTrue(any("{app}" in template for template in seen))
+ self.assertFalse(any("PrivateApp.exe" in template for template in seen))
+
+
+class NativePrototypeTests(unittest.TestCase):
+ def test_handle_and_sid_results_are_pointer_sized_and_dwords_stay_32_bit(self):
+ user32, kernel32, advapi32 = mock.Mock(), mock.Mock(), mock.Mock()
+ input_blocker._configure_apis(user32, kernel32, advapi32)
+ self.assertEqual(ctypes.sizeof(input_blocker.DWORD), 4)
+ self.assertIs(user32.GetForegroundWindow.restype, ctypes.c_void_p)
+ self.assertEqual(user32.GetForegroundWindow.argtypes, [])
+ self.assertIs(kernel32.OpenProcess.restype, ctypes.c_void_p)
+ self.assertIs(kernel32.CloseHandle.argtypes[0], ctypes.c_void_p)
+ self.assertIs(user32.GetClassNameW.argtypes[0], ctypes.c_void_p)
+ self.assertIs(user32.GetWindowThreadProcessId.argtypes[0], ctypes.c_void_p)
+ self.assertIs(advapi32.OpenProcessToken.argtypes[0], ctypes.c_void_p)
+ self.assertIs(advapi32.OpenProcessToken.argtypes[2]._type_, ctypes.c_void_p)
+ self.assertIs(advapi32.GetTokenInformation.argtypes[0], ctypes.c_void_p)
+ self.assertEqual(ctypes.sizeof(advapi32.GetSidSubAuthority.restype), ctypes.sizeof(ctypes.c_void_p))
+ self.assertEqual(ctypes.sizeof(input_blocker.SID_AND_ATTRIBUTES),
+ 16 if ctypes.sizeof(ctypes.c_void_p) == 8 else 8)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_installer_maintenance.py b/win_app/tests/test_installer_maintenance.py
index c89488b..ed107a7 100644
--- a/win_app/tests/test_installer_maintenance.py
+++ b/win_app/tests/test_installer_maintenance.py
@@ -63,6 +63,152 @@ class MaintenanceBehaviourTests(unittest.TestCase):
)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ def test_explicit_administrator_preference_survives_upgrade(self):
+ self.run_probe(r'''
+$script:registered = @()
+function Get-BeamerAdministratorPreference($UserSid) { return $true }
+function Resolve-BeamerUserSid($Identity) { return $Identity }
+function Get-ScheduledTask { param($TaskPath, $ErrorAction)
+ return @([pscustomobject]@{ TaskName='Beamer-owner'; TaskPath='\' })
+}
+function Export-ScheduledTask { param($TaskName, $TaskPath, $ErrorAction)
+ return '<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Triggers><LogonTrigger><Enabled>false</Enabled></LogonTrigger></Triggers><Principals><Principal><UserId>S-1-5-21-123</UserId><LogonType>InteractiveToken</LogonType><RunLevel>HighestAvailable</RunLevel></Principal></Principals><Settings><Enabled>false</Enabled></Settings><Actions><Exec><Command>C:\Beamer\Beamer.exe</Command><Arguments>--hidden --keep-this</Arguments></Exec></Actions></Task>'
+}
+function Register-ScheduledTask { param($TaskName, $TaskPath, $Xml, [switch]$Force, $ErrorAction)
+ $script:registered += $Xml
+}
+Update-BeamerAutostart -ExePath 'C:\Beamer\Beamer.exe' -UserSid 'S-1-5-21-123'
+if ($script:registered.Count) { throw 'Upgrade rewrote an opted-in administrator task' }
+''')
+
+ def test_upgrade_preserves_omitted_default_runlevel_without_registration(self):
+ self.run_probe(r'''
+$script:registered = @()
+function Get-BeamerAdministratorPreference($UserSid) { return $false }
+function Resolve-BeamerUserSid($Identity) { return $Identity }
+function Get-ScheduledTask { param($TaskPath, $ErrorAction)
+ return @([pscustomobject]@{ TaskName='Beamer-owner'; TaskPath='\' })
+}
+function Export-ScheduledTask { param($TaskName, $TaskPath, $ErrorAction)
+ return '<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Principals><Principal><UserId>S-1-5-21-123</UserId><LogonType>InteractiveToken</LogonType></Principal></Principals><Actions><Exec><Command>C:\Beamer\Beamer.exe</Command></Exec></Actions></Task>'
+}
+function Register-ScheduledTask { param($TaskName, $TaskPath, $Xml, [switch]$Force, $ErrorAction)
+ $script:registered += $Xml
+}
+Update-BeamerAutostart -ExePath 'C:\Beamer\Beamer.exe' -UserSid 'S-1-5-21-123'
+if ($script:registered.Count) { throw 'Upgrade rewrote the existing default-privilege task' }
+''')
+
+ def test_upgrade_materialises_omitted_runlevel_only_for_administrator_preference(self):
+ self.run_probe(r'''
+$script:registered = @()
+$script:original = '<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Triggers><LogonTrigger><Enabled>false</Enabled></LogonTrigger></Triggers><Principals><Principal id="Author"><UserId>S-1-5-21-123</UserId><LogonType>InteractiveToken</LogonType></Principal></Principals><Settings><Enabled>false</Enabled></Settings><Actions Context="Author"><Exec><Command>C:\Beamer\Beamer.exe</Command><Arguments>--hidden --keep-this</Arguments></Exec></Actions></Task>'
+function Get-BeamerAdministratorPreference($UserSid) { return $true }
+function Resolve-BeamerUserSid($Identity) { return $Identity }
+function Get-ScheduledTask { param($TaskPath, $ErrorAction)
+ return @([pscustomobject]@{ TaskName='Beamer-owner'; TaskPath='\' })
+}
+function Export-ScheduledTask { param($TaskName, $TaskPath, $ErrorAction) return $script:original }
+function Register-ScheduledTask { param($TaskName, $TaskPath, $Xml, [switch]$Force, $ErrorAction)
+ $script:registered += $Xml
+}
+Update-BeamerAutostart -ExePath 'C:\Beamer\Beamer.exe' -UserSid 'S-1-5-21-123'
+if ($script:registered.Count -ne 1) { throw 'Expected exactly one administrator task update' }
+[xml]$actual = $script:registered[0]
+$ns = New-Object Xml.XmlNamespaceManager($actual.NameTable)
+$ns.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task')
+$runLevel = $actual.SelectSingleNode('/t:Task/t:Principals/t:Principal/t:RunLevel', $ns)
+if ($null -eq $runLevel -or $runLevel.InnerText -ne 'HighestAvailable') { throw 'Upgrade did not add the namespaced administrator run level' }
+[void]$runLevel.ParentNode.RemoveChild($runLevel)
+[xml]$wanted = $script:original
+if ($actual.OuterXml -ne $wanted.OuterXml) { throw 'Upgrade changed existing task choices' }
+''')
+
+ def test_gameinput_recovery_registers_only_fixed_system_action_and_run_permissions(self):
+ self.run_probe(r'''
+$script:registrations = @()
+$script:action = [pscustomobject]@{ Path=''; Arguments=''; WorkingDirectory='' }
+$actions = [pscustomobject]@{ Count=0 }
+$actions | Add-Member ScriptMethod Create {
+ param($type)
+ if ($type -ne 0) { throw 'Recovery must use one executable action' }
+ $this.Count++
+ return $script:action
+}
+$script:definition = [pscustomobject]@{
+ RegistrationInfo=[pscustomobject]@{ Description='' }
+ Principal=[pscustomobject]@{ UserId=''; LogonType=0; RunLevel=0 }
+ Settings=[pscustomobject]@{ Enabled=$false; AllowDemandStart=$false; DisallowStartIfOnBatteries=$true; StopIfGoingOnBatteries=$true; ExecutionTimeLimit=''; MultipleInstances=0 }
+ Triggers=[pscustomobject]@{ Count=0 }
+ Actions=$actions
+}
+$script:folder = [pscustomobject]@{}
+$script:folder | Add-Member ScriptMethod RegisterTaskDefinition {
+ param($name, $definition, $flags, $userId, $password, $logonType, $sddl)
+ $script:registrations += [pscustomobject]@{ Name=$name; Definition=$definition; Flags=$flags; UserId=$userId; Password=$password; LogonType=$logonType; Sddl=$sddl }
+}
+$script:scheduler = [pscustomobject]@{}
+$script:scheduler | Add-Member ScriptMethod Connect {}
+$script:scheduler | Add-Member ScriptMethod GetFolder {
+ param($path)
+ if ($path -ne '\') { throw 'Recovery task escaped the root folder' }
+ return $script:folder
+}
+$script:scheduler | Add-Member ScriptMethod NewTask {
+ param($flags)
+ if ($flags -ne 0) { throw 'Unexpected task definition flags' }
+ return $script:definition
+}
+function New-Object { param($ComObject)
+ if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM server' }
+ return $script:scheduler
+}
+Update-BeamerGameInputRecovery
+if ($script:registrations.Count -ne 1) { throw 'Expected exactly one task registration' }
+$registration = $script:registrations[0]
+if ($registration.Name -ne 'Beamer-GameInputRecovery') { throw 'Recovery task name is not fixed' }
+if ($registration.UserId -ne 'S-1-5-18' -or $registration.Password -or $registration.LogonType -ne 5) { throw 'Recovery must run as SYSTEM without a password' }
+if ($script:definition.Principal.UserId -ne 'S-1-5-18' -or $script:definition.Principal.LogonType -ne 5) { throw 'Task principal disagrees with registration' }
+if (($registration.Flags -band 6) -ne 6) { throw 'Reinstall must replace the task definition' }
+if ($script:definition.Triggers.Count -ne 0 -or -not $script:definition.Settings.AllowDemandStart -or -not $script:definition.Settings.Enabled) { throw 'Recovery must be enabled and on demand only' }
+if ($script:definition.Settings.DisallowStartIfOnBatteries -or $script:definition.Settings.StopIfGoingOnBatteries) { throw 'Recovery must work on battery power' }
+if ($script:definition.Settings.MultipleInstances -ne 2 -or $script:definition.Settings.ExecutionTimeLimit -ne 'PT30S') { throw 'Recovery must not queue or run indefinitely' }
+if ($actions.Count -ne 1) { throw 'Expected exactly one action' }
+$windows = [Environment]::GetFolderPath([Environment+SpecialFolder]::Windows)
+if ($script:action.Path -cne (Join-Path $windows 'System32\WindowsPowerShell\v1.0\powershell.exe')) { throw 'Privileged action must use the absolute Windows PowerShell path' }
+if ($script:action.Arguments -cne '-NoLogo -NoProfile -NonInteractive -Command "Restart-Service -Name ''GameInputSvc'' -ErrorAction Stop"') { throw 'Recovery action accepts something other than the constant service restart' }
+if ($script:action.WorkingDirectory -cne (Join-Path $windows 'System32')) { throw 'Recovery uses a user-writable working directory' }
+$sd = [Security.AccessControl.RawSecurityDescriptor]::new($registration.Sddl)
+if ($sd.Owner.Value -ne 'S-1-5-18' -or $sd.Group.Value -ne 'S-1-5-18') { throw 'Interactive user can own or change the task' }
+if (-not ($sd.ControlFlags -band [Security.AccessControl.ControlFlags]::DiscretionaryAclProtected)) { throw 'Task permissions can inherit write access' }
+if ($sd.DiscretionaryAcl.Count -ne 3) { throw 'Unexpected task permission grants' }
+$expected = @{ 'S-1-5-18'=268435456; 'S-1-5-32-544'=268435456; 'S-1-5-4'=-1610612736 }
+foreach ($ace in $sd.DiscretionaryAcl) {
+ $sid = $ace.SecurityIdentifier.Value
+ if (-not $expected.ContainsKey($sid) -or $ace.AccessMask -ne $expected[$sid] -or $ace.AceQualifier -ne [Security.AccessControl.AceQualifier]::AccessAllowed) { throw 'Task permissions allow changing or deleting the privileged action' }
+ $expected.Remove($sid)
+}
+if ($expected.Count) { throw 'Missing recovery task permissions' }
+''')
+
+ def test_gameinput_recovery_uninstall_removes_only_fixed_task_and_is_idempotent(self):
+ self.run_probe(r'''
+$script:removed = @()
+$script:present = $true
+function New-Object { throw 'Uninstall must not create a task definition' }
+function Get-ScheduledTask { param($TaskName, $TaskPath, $ErrorAction)
+ if ($TaskName -ne 'Beamer-GameInputRecovery' -or $TaskPath -ne '\') { throw 'Uninstall queried unrelated tasks' }
+ if ($script:present) { return [pscustomobject]@{ TaskName=$TaskName; TaskPath=$TaskPath } }
+}
+function Unregister-ScheduledTask { param($TaskName, $TaskPath, $Confirm, $ErrorAction)
+ $script:removed += [pscustomobject]@{ Name=$TaskName; Path=$TaskPath }
+ $script:present = $false
+}
+Update-BeamerGameInputRecovery -Remove
+Update-BeamerGameInputRecovery -Remove
+if ($script:removed.Count -ne 1 -or $script:removed[0].Name -ne 'Beamer-GameInputRecovery' -or $script:removed[0].Path -ne '\') { throw 'Uninstall removed another task or failed when already absent' }
+''')
+
def test_migration_preserves_choices_and_ignores_other_users_and_actions(self):
self.run_probe(r'''
$script:registered = @()
diff --git a/win_app/tests/test_no_uac_runtime.py b/win_app/tests/test_no_uac_runtime.py
index a86247f..0bafa21 100644
--- a/win_app/tests/test_no_uac_runtime.py
+++ b/win_app/tests/test_no_uac_runtime.py
@@ -9,12 +9,19 @@ from unittest.mock import patch
import desktop_win
import firewall_win
import input_injector
+from input_blocker import ForegroundBlocker
class OrdinaryInputTests(unittest.TestCase):
+ def setUp(self):
+ notified = patch.object(input_injector, "_problem_notified", set())
+ notified.start()
+ self.addCleanup(notified.stop)
+
def test_sendinput_refusal_reports_problem_without_spamming(self):
notices = []
with patch.object(input_injector, "user32", SimpleNamespace(SendInput=lambda *a: 0)), \
+ patch.object(input_injector, "foreground_blocker", return_value=ForegroundBlocker(process_name="admin.exe", elevated=True)), \
patch.object(input_injector, "on_problem", notices.append, create=True), \
patch.object(input_injector, "_problem_at", float("-inf"), create=True), \
patch.object(ctypes, "get_last_error", return_value=0, create=True):
@@ -22,7 +29,7 @@ class OrdinaryInputTests(unittest.TestCase):
with self.assertRaises(OSError):
input_injector._send_input(input_injector.INPUT())
self.assertEqual(len(notices), 1)
- self.assertIn("locally", notices[0])
+ self.assertIn("admin.exe", notices[0])
def test_successful_input_has_no_warning(self):
notices = []
@@ -31,22 +38,25 @@ class OrdinaryInputTests(unittest.TestCase):
input_injector._send_input(input_injector.INPUT())
self.assertEqual(notices, [])
- def test_gameinput_refusal_never_runs_service_maintenance(self):
+ def test_gameinput_refusal_delegates_recovery_without_inline_maintenance(self):
notices, commands = [], []
with patch.object(input_injector, "foreground_class", return_value="GameInputServiceWindow"), \
+ patch.object(input_injector, "foreground_blocker", return_value=ForegroundBlocker(window_class="GameInputServiceWindow")), \
+ patch.object(input_injector, "_gameinput_running", False), \
+ patch.object(input_injector, "_gameinput_restarted_at", float("-inf")), \
patch.object(input_injector, "on_problem", notices.append, create=True), \
patch.object(input_injector, "_problem_at", float("-inf"), create=True), \
patch.object(subprocess, "run", side_effect=lambda *a, **k: commands.append(a)), \
patch.object(input_injector.threading, "Thread") as thread:
- self.assertFalse(input_injector.release_gameinput_foreground())
+ self.assertTrue(input_injector.release_gameinput_foreground())
self.assertEqual(commands, [])
- thread.assert_not_called()
+ thread.return_value.start.assert_called_once()
self.assertEqual(len(notices), 1)
def test_failed_cursor_placement_reports_problem(self):
notices = []
with patch.object(desktop_win, "user32", SimpleNamespace(SetCursorPos=lambda *a: 0)), \
- patch.object(input_injector, "foreground_class", return_value="AdminWindow"), \
+ patch.object(input_injector, "foreground_blocker", return_value=ForegroundBlocker(window_class="AdminWindow", process_name="admin.exe", elevated=True)), \
patch.object(input_injector, "on_problem", notices.append, create=True), \
patch.object(input_injector, "_problem_at", float("-inf"), create=True), \
patch.object(desktop_win, "_refused_under", [None]), \